示例#1
0
        public CustomFaker(string locale, double mistakesNumber)
        {
            switch (locale)
            {
            case "en_US":
                this.locale = "en_US";
                break;

            case "ru_RU":
                this.locale = "ru";
                break;

            case "be_BY":
                this.locale = "be";
                break;

            default:
                throw new ArgumentException($"Unsupported locale: {locale}");
            }

            this.mistakesNumber = mistakesNumber;
            nameDataSet         = new Bogus.DataSets.Name(this.locale);
            addressDataSet      = new Bogus.DataSets.Address(this.locale);
            phoneNumbersDataSet = new Bogus.DataSets.PhoneNumbers(this.locale);
            loremDataSet        = new Bogus.DataSets.Lorem(this.locale);
            random = new Random();
        }
示例#2
0
        static void Main()
        {
            var random    = new Randomizer();
            var lorem     = new Bogus.DataSets.Lorem();
            var addresses = new Bogus.DataSets.Address();

            var order = new Order()
            {
                OrderId  = random.Number(1, 100),
                Item     = string.Join(" ", lorem.Letter(100)),
                Quantity = random.Number(1, 10),
                ZipCode  = addresses.ZipCode()
            };

            order.Dump();

            Console.ReadLine();
            var fruit = new[] { "apple", "banana", "orange", "strawberry", "kiwi", "grapefruit" };

            var testOrders = new Faker <Order>()
                             //Ensure all properties have rules. By default, StrictMode is false
                             //Set a global policy by using Faker.DefaultStrictMode
                             .StrictMode(true)
                             //OrderId is deterministic
                             .RuleFor(o => o.OrderId, f => f.Random.Number(1, 100))
                             //Pick some fruit from a basket
                             .RuleFor(o => o.Item, f => f.PickRandom(fruit))
                             //A random quantity from 1 to 10
                             .RuleFor(o => o.Quantity, f => f.Random.Number(1, 10))
                             .RuleFor(o => o.ZipCode, f => f.Address.ZipCode());

            testOrders.Generate(3).ToList().ForEach(o => o.Dump());
            Console.ReadLine();
        }
示例#3
0
        public void Assign_MoreThan256Characters_to_SongTitleAlbumComposer_ReturnsError(string locale)
        {
            //arrange
            var lorem = new Bogus.DataSets.Lorem(locale: locale)
            {
                Random = new Randomizer(1080)
            };

            Song fakeSong = new Song()
            {
                Title    = lorem.Letter(257),
                Album    = lorem.Letter(257),
                Composer = lorem.Letter(257)
            };

            SongValidator    validator = new SongValidator();
            ValidationResult results   = validator.Validate(fakeSong);

            bool isValid = results.IsValid;
            IList <ValidationFailure> failures = results.Errors;

            Assert.False(isValid);
            foreach (var failure in failures)
            {
                _output.WriteLine(failure.ErrorMessage);
            }
        }
        public RequestDto GetRequest()
        {
            var random = new Bogus.Randomizer();
            var lorem  = new Bogus.DataSets.Lorem();

            var subRequest = new Faker <SubRequestDto>()
                             .RuleFor(first => first.Name, f => lorem.Text())
                             .RuleFor(first => first.ChildID, f => random.Number(1990, 2030))
                             .RuleFor(first => first.DateOfBirth, f => f.Date.Recent(100));

            var requestDto = new RequestDto()
            {
                Year           = random.Number(1990, 2030),
                Denomination1  = lorem.Text(),
                Denomination2  = lorem.Text(),
                MaritalStatus  = random.Word(),
                SubRequests    = subRequest.Generate(2),
                Income         = (decimal)random.Number(10000, 2564789),
                QualifiedProp  = (decimal)random.Number(10000, 2564789),
                QualifiedProp2 = (decimal)random.Number(10000, 2564789),
                SomeProp       = (decimal)random.Number(10000, 2564789),
                SomeProp2      = (decimal)random.Number(10000, 2564789),
                SomeProp3      = (decimal)random.Number(10000, 2564789),
                Shortname      = random.Word(),
                SomeProp22     = random.Word(),
            };

            return(requestDto);
        }
示例#5
0
        protected override void Seed(ToDoDotNet.Data.ToDoDbContext context)
        {
            var lorem = new Bogus.DataSets.Lorem();
            var dates = new Bogus.DataSets.Date();

            context.ToDos.AddOrUpdate(x => x.Id,
                                      new ToDo()
            {
                Title = lorem.Word(), Body = lorem.Sentences(), CreationDate = dates.Soon()
            },
                                      new ToDo()
            {
                Title = lorem.Word(), Body = lorem.Sentences(), CreationDate = dates.Soon()
            },
                                      new ToDo()
            {
                Title = lorem.Word(), Body = lorem.Sentences(), CreationDate = dates.Soon()
            },
                                      new ToDo()
            {
                Title = lorem.Word(), Body = lorem.Sentences(), CreationDate = dates.Soon()
            },
                                      new ToDo()
            {
                Title = lorem.Word(), Body = lorem.Sentences(), CreationDate = dates.Soon()
            }
                                      );
        }
        public async Task TestCreateValidBelgianShipment()
        {
            var address = new Bogus.Faker <Models.Address>()
                          .RuleFor(a => a.EmailAddress, f => f.Internet.ExampleEmail())
                          .RuleFor(a => a.Country, f => "BE")
                          .RuleFor(a => a.StreetName, f => "Rue Brederode")
                          .RuleFor(a => a.Locality, f => "Brussel")
                          .RuleFor(a => a.ZipCode, f => "1000")
                          .RuleFor(a => a.HouseNumber, f => "16")
                          .RuleFor(a => a.EoriNumber, f => "BE1682949223")
                          .RuleFor(a => a.VatNumber, f => "BE1682949223")
                          .RuleFor(a => a.Givenname, f => f.Name.FirstName())
                          .RuleFor(a => a.FamilyName, f => f.Name.LastName());

            var orderLine = new Bogus.Faker <Models.OrderLine>()
                            .RuleFor(ol => ol.CountryOfOrigin, f => "BE")
                            .RuleFor(ol => ol.Description, f => f.Commerce.ProductDescription())
                            .RuleFor(ol => ol.SKU, f => f.Commerce.Ean13())
                            .RuleFor(ol => ol.EAN, f => f.Commerce.Ean13())
                            .RuleFor(ol => ol.HsCode, f => "22030001")
                            .RuleFor(ol => ol.Weight, f => f.Random.Int(200, 1000))
                            .RuleFor(ol => ol.Value, f => f.Finance.Amount(5, 20, 2) * 100)
                            .RuleFor(ol => ol.Quantity, f => f.Random.Int(1, 5));


            var lorem      = new Bogus.DataSets.Lorem(locale: "en");
            var orderlines = orderLine.Generate(3);

            var generateShipment = new Bogus.Faker <Requests.CreateShipmentRequest>()
                                   .RuleFor(s => s.Description, f => lorem.Sentence(1))
                                   .RuleFor(s => s.DeliveryAddress, f => address.Generate())
                                   .RuleFor(s => s.PreferredServiceLevel, f => Models.Constants.ShippingServiceLevels.Where(dl => dl.Contains("dpd") && dl.Contains("be") && dl.Contains("cheap")).FirstOrDefault()) // f.PickRandom(Models.Constants.ShippingServiceLevels)
                                   .RuleFor(s => s.Kind, "package")
                                   .RuleFor(s => s.Value, f => f.Random.Int(1, 50))
                                   .RuleFor(s => s.OrderLines, f => orderlines)
                                   .RuleFor(s => s.NumberOfItems, f => 1)
                                   .RuleFor(s => s.Length, f => 35)
                                   .RuleFor(s => s.Width, f => 35)
                                   .RuleFor(s => s.Height, f => 35)
                                   .RuleFor(s => s.Weight, f => orderlines.Sum(dl => dl.Quantity * dl.Weight));



            var request = generateShipment.Generate();

            foreach (var reqItem in request.OrderLines)
            {
                if (!string.IsNullOrEmpty(reqItem.HsCode) && reqItem.HsCode.ToString().Length == 8)
                {
                    reqItem.HsCode = "00" + reqItem.HsCode;
                }
            }

            var response = await client.CreateShipment(request);

            Assert.IsNotNull(response);
        }
示例#7
0
        public Article()
        {
            Id       = Guid.NewGuid();
            AuthorId = Guid.NewGuid();
            var lorem = new Bogus.DataSets.Lorem();

            Title       = lorem.Sentence();
            Description = lorem.Paragraph(5);
        }
        /// <summary>
        /// Создает новый экземпляр сгенерированных данных о сериях
        /// </summary>
        public FakeEpisodeEntities()
        {
            var loremRu = new Bogus.DataSets.Lorem("ru");

            EpisodeFaker = new Faker <EpisodeEntity>()
                           .RuleFor(m => m.Id, f => f.IndexFaker)
                           .RuleFor(m => m.TitleRu, f => string.Join(" ", loremRu.Words(2)))
                           .RuleFor(m => m.TitleEn, f => string.Join(" ", f.Lorem.Words(2)))
                           .RuleFor(m => m.DurationInMinutes, f => f.Random.Double(15, 60))
                           .RuleFor(m => m.UrlForEpisodeSource, f => f.Internet.Url());

            EpisodeEntities = new List <EpisodeEntity>();
        }
示例#9
0
        public void Start(CancellationTokenSource token)
        {
            InitializeLogger();

            var lorem = new Bogus.DataSets.Lorem();
            var sw    = Stopwatch.StartNew();

            while (!token.IsCancellationRequested)
            {
                int logType = _random.Next(1, 4);
                int appId   = _random.Next(1, 6);
                var message = lorem.Sentence(_random.Next(3, 10));

                _backendLogger
                .ForContext("Application", GetAppName(appId))
                .ForContext(nameof(Environment.UserName), Environment.UserName)
                .ForContext("ElapsedMilliseconds", sw.ElapsedMilliseconds);

                sw.Restart();

                switch (logType)
                {
                case 2:
                {
                    _backendLogger.Warning(message);
                    break;
                }

                case 3:
                {
                    _backendLogger.Error(new Exception(message), "An error occured");
                    break;
                }

                case 4:
                {
                    _frontendLogger.Error(new Exception(message), "Frontend - An error occured");
                    break;
                }

                default:
                {
                    _backendLogger.Information(message);
                    break;
                }
                }

                int delay = _random.Next(200, 1300);
                Thread.Sleep(delay);
            }
        }
示例#10
0
        public FormMain()
        {
            InitializeComponent();

            this.lorem = new Bogus.DataSets.Lorem("en");

            this.boxConsole.TopRowChanged    += (s, e) => UpdateText();
            this.boxConsole.BottomRowChanged += (s, e) => UpdateText();

            this.boxConsole.DrawMode          = TextDrawMode.ExtTextOut;
            this.boxConsole.BufferSize        = 200;
            this.boxConsole.AutoScrollLastRow = true;
            this.timerAddRows.Interval        = 1;
            //this.timerAddRows.Enabled = false;
        }
示例#11
0
        public int Seed(AppDbContext context)
        {
            var lorem = new Bogus.DataSets.Lorem();

            var faker = new Faker <Product>()
                        .RuleFor(r => r.Sku, f => f.Random.AlphaNumeric(8))
                        .RuleFor(r => r.Title, f => f.Random.Word())
                        .RuleFor(r => r.Category, () => context.Categories.Where(c => !c.IsGroup).OrderBy(o => Guid.NewGuid()).First())
                        .RuleFor(r => r.Description, () => lorem.Sentence(14));

            var prod = faker.Generate(50);

            context.AddRange(prod);
            context.SaveChanges();
            return(prod.Count);
        }
        /// <summary>
        /// Создает новый экземпляр сгенерированных данных о сериалах
        /// </summary>
        /// <param name="personsCount">Необходимое количество сгенерированных людей</param>
        /// <param name="genresCount">Необходимое количество сгенерированных жанров видео</param>
        /// <param name="tvSerialsCount">Необходимое количество сгенерированных сериалах</param>
        public FakeTvSeriasEntities(
            int tvSeriasCount,
            FakePersonEntities personEntities,
            FakeGenreEntities genreEntities,
            FakeSeasonEntities seasonEntities,
            FakeEpisodeEntities episodeEntities)
        {
            var loremRu = new Bogus.DataSets.Lorem("ru");

            TvSeriasFaker = new Faker <TvSeriasEntity>()
                            .RuleFor(m => m.Id, f => f.IndexFaker)
                            .RuleFor(m => m.TitleEn, f => string.Join(" ", f.Lorem.Words(2)))
                            .RuleFor(m => m.TitleEn, f => string.Join(" ", loremRu.Words(2)))
                            .RuleFor(m => m.PosterImageUrl, f => f.Internet.Url())
                            .RuleFor(m => m.LostfilmRate, f => f.Random.Double(1, 10))
                            .RuleFor(m => m.RateImDb, f => f.Random.Double(1, 10))
                            .RuleFor(m => m.UrlToOfficialSite, f => f.Internet.Url())
                            .RuleFor(m => m.Summary, f => f.Lorem.Text())
                            .RuleFor(m => m.ListPerson, f => f.PickRandom(personEntities.PersonEntities, 30).ToList())
                            .RuleFor(m => m.ListGenreEntity, f => f.PickRandom(genreEntities.GenreEntities, 3).ToList())
                            .RuleFor(m => m.ListSeasons, f => seasonEntities.Generate(
                                         f.Random.Number(1, 13),
                                         f.Date.Between(new DateTime(1995, 1, 1), new DateTime(2020, 12, 31)),
                                         episodeEntities));

            TvSeriasEntities = TvSeriasFaker.Generate(tvSeriasCount);

            foreach (var tvSeriasEntity in TvSeriasEntities)
            {
                foreach (var seasonEntity in tvSeriasEntity.ListSeasons)
                {
                    seasonEntity.TvSeriesId = tvSeriasEntity.Id;
                    seasonEntity.TvSeries   = tvSeriasEntity;
                }

                foreach (var genreEntity in tvSeriasEntity.ListGenreEntity)
                {
                    genreEntity.ListTvSerias.Add(tvSeriasEntity);
                }

                foreach (var personEntity in tvSeriasEntity.ListPerson)
                {
                    personEntity.ListTvSerias.Add(tvSeriasEntity);
                }
            }
        }
        private static IEnumerable <Message> RandomMessages()
        {
            Random         random       = new Random();
            List <Message> messages     = new List <Message>();
            var            bogusMessage = new Bogus.DataSets.Lorem();
            var            person       = new Bogus.Person();

            for (int i = 0; i < random.Next(1, 5); i++)
            {
                messages.Add(new Message(
                                 bogusMessage.Paragraph(),
                                 person.FirstName,
                                 person.LastName,
                                 person.Email
                                 ));
            }

            return(messages);
        }
        public CustomerFaker()
        {
            var lorem = new Bogus.DataSets.Lorem(locale: "pl");

            UseSeed(1);
            RuleFor(p => p.Id, f => f.IndexFaker);
            RuleFor(p => p.FirstName, f => f.Person.FirstName);
            RuleFor(p => p.LastName, f => f.Person.LastName);
            RuleFor(p => p.Gender, f => (Gender)f.Person.Gender);
            RuleFor(p => p.Email, (f, customer) => $"{customer.FirstName}.{customer.LastName}@domain.com"); // [email protected]
            RuleFor(p => p.Description, f => lorem.Sentences(3));
            RuleFor(p => p.Birthday, f => f.Person.DateOfBirth);
            RuleFor(p => p.Type, f => f.PickRandom <CustomerType>());
            RuleFor(p => p.CreditAmount, f => f.Random.Decimal(1m, 1000m).OrNull(f, 0.3f));
            RuleFor(p => p.IsRemoved, f => f.Random.Bool(0.2f));
            RuleFor(p => p.Pesel, f => f.Person.Pesel());

            RuleFor(p => p.Username, f => f.Person.UserName);
            RuleFor(p => p.HashedPassword, f => "12345");
        }
示例#15
0
        /// <summary>
        /// A mock for the "TranslateText" method of Google Translate
        /// The method recevies a source language, target languages and a list of texts
        /// and returns a list of translations for the given texts
        /// The mock uses a lorem ipsum library for faking data
        /// </summary>
        /// <param name="sourceLanguage">Current language used in the HTML file</param>
        /// <param name="targetLanguage">The desired translation language</param>
        /// <param name="texts">A list of texts for translations</param>
        /// <returns>Returns a list of translations for the given texts</returns>
        public TranslateTextResponseList TranslateText(string sourceLanguage, string targetLanguage, IList <string> texts)
        {
            Randomizer.Seed = new Random(texts.Count);
            var lorem        = new Bogus.DataSets.Lorem(locale: "ko"); // Using korean, since the library cannot fake Japanese data sets
            var translations = new List <TranslateTextResponseTranslation>();

            for (int idx = 0; idx < texts.Count; idx++)
            {
                translations.Add(new TranslateTextResponseTranslation()
                {
                    DetectedSourceLanguage = targetLanguage,
                    TranslatedText         = lorem.Sentence()
                });
            }

            return(new TranslateTextResponseList()
            {
                Translations = translations
            });
        }
        public IEnumerable <Application> GetApplications()
        {
            var applicationId     = 1;
            var applicationData   = new Bogus.DataSets.Lorem("en");
            var applicationStatus = new[] { "New", "App Team Engaged", "Analyzed", "Disposition Initiated", "Dispositioned", "Deployed" };

            Randomizer.Seed = new Random(123789);

            var applicationGenerator = new Faker <Application>()
                                       .RuleFor(app => app.Id, mck => $"CA {applicationId++}")
                                       .RuleFor(app => app.Name, mck => String.Join(" ", applicationData.Words(4)))
                                       .RuleFor(app => app.RemedyId, mck => $"OI-{Guid.NewGuid()}")
                                       .RuleFor(app => app.Description, mck => applicationData.Sentence(8))
                                       .RuleFor(app => app.ShortAppId, mck => applicationData.Word())
                                       .RuleFor(app => app.Status, mck => mck.PickRandom(applicationStatus))
                                       .RuleFor(app => app.InstallDate, mck => mck.Date.Past(5).Date)
                                       .RuleFor(app => app.IsHighRisk, mck => mck.Random.Bool());

            return(applicationGenerator.Generate(100));
        }
示例#17
0
        public void TestMe()
        {
            var lorem = new Bogus.DataSets.Lorem();

            var originalData = "{\"secret\":\"" + lorem.Sentence(8) + "\"}";

            Console.WriteLine(originalData);

            var redactData = RedactViaReverseProxy(originalData).Result;

            Console.WriteLine(redactData);
            Assert.NotEqual(originalData, redactData);

            var revealData = RevealViaForwardProxy(redactData).Result;

            Console.WriteLine(revealData);
            Assert.NotEqual(revealData, redactData);

            Assert.Equal(originalData, revealData);
            Console.WriteLine("Test passed");
        }
示例#18
0
文件: UnitTest1.cs 项目: cashwu/Bogus
        public void Test1()
        {
            var userGenerator = new Faker <User>("zh_TW")
                                .RuleFor(a => a.Id, b => b.IndexFaker)
                                .RuleFor(a => a.Guid, b => b.Random.Guid())
                                .RuleFor(a => a.FirstName, (b, a) => b.Name.FirstName())
                                .RuleFor(a => a.LastName, (b, a) => b.Name.LastName())
                                .RuleFor(a => a.Gender, b => b.Person.Gender)
                                .RuleFor(a => a.Email, b => b.Image.PicsumUrl())
                                .RuleFor(a => a.BirthDate, b => b.Date.Future());

            var users = userGenerator.GenerateForever().Take(10);

            foreach (var user in users)
            {
                _outputHelper.WriteLine(user.ToString());
            }

            var lorem = new Bogus.DataSets.Lorem("zh_TW");

            _outputHelper.WriteLine(lorem.Sentence(10));
        }
示例#19
0
        public void GameSong_MustBeAssociatedWith_EitherGameOrDlc(string locale)
        {
            var lorem = new Bogus.DataSets.Lorem(locale)
            {
                Random = new Randomizer(1080)
            };

            Game fakeGame = new Game()
            {
                Title = lorem.Letter(1)
            };

            Song fakeSong = new Song()
            {
                Title    = lorem.Letter(1),
                Composer = lorem.Letter((1)),
                Album    = lorem.Letter(1)
            };
            var randomFluent = new Bogus.Faker()
            {
                Random = new Randomizer(1080)
            };
            DifficultyMode fakeMode = new DifficultyMode();

            fakeMode.Level    = randomFluent.Random.Int(1, 20);
            fakeMode.Category = DifficultyCategory.Easy;

            Ez2OnGameTrack fakeGameTrack = new Ez2OnGameTrack(fakeSong, fakeGame, fakeMode);

            SongValidator fakeSongValidator = new SongValidator();
            GameValidator fakeGameValidator = new GameValidator();

            GameTrackValidator mockValidator = new GameTrackValidator(fakeSongValidator, fakeGameValidator);

            var gameMusicResults = mockValidator.Validate(fakeGameTrack);

            Assert.True(gameMusicResults.IsValid);
        }
示例#20
0
        static void Main(string[] args)
        {
            Program program = new Program(2);

            var lorem    = new Bogus.DataSets.Lorem("en");
            var testUser = new Faker <PlayerDetails>()
                           .StrictMode(true)
                           .RuleFor(o => o.UserName, f => lorem.Word())
                           .RuleFor(o => o.Rating, f => f.Random.Number(300, 3000));

            program.players = testUser.Generate(100);

            program.players = program.players.OrderBy(x => x.Rating).ToList();

            program.match.teams = new List <List <PlayerDetails> >();

            for (int i = 0; i < program.numberOfTeams; i++)
            {
                program.match.teams.Add(BuildTeam(program, program.numberOfTeams - i));
            }

            Console.WriteLine(program.match);
        }
示例#21
0
        public static string RadomSentence(int?wordCount = null)
        {
            var lorem = new Bogus.DataSets.Lorem();

            return(lorem.Sentence(wordCount));
        }