Coder Social home page Coder Social logo

bchavez / bogus Goto Github PK

View Code? Open in Web Editor NEW
8.4K 122.0 478.0 6.09 MB

:card_index: A simple fake data generator for C#, F#, and VB.NET. Based on and ported from the famed faker.js.

License: Other

C# 98.48% Batchfile 0.01% JavaScript 1.10% PowerShell 0.24% Shell 0.16%
fake data generator dotnet csharp faker c-sharp bogus poco data-access-layer

bogus's Introduction

Downloads Build status Twitter Chat

Bogus for .NET: C#, F#, and VB.NET

Project Description

Hello. I'm your host Brian Chavez (twitter). Bogus is a simple fake data generator for .NET languages like C#, F# and VB.NET. Bogus is fundamentally a C# port of faker.js and inspired by FluentValidation's syntax sugar.

Bogus will help you load databases, UI and apps with fake data for your testing needs. If you like Bogus star ⭐ the repository and show your friends! πŸ˜„ If you find Bogus useful consider supporting the project by purchasing a Bogus Premium license that gives you extra Bogus superpowers! πŸ’« πŸ’ͺ You can also sponsor the project here! πŸ’° πŸ’΅

Download & Install

Nuget Package Bogus

Install-Package Bogus

Minimum Requirements: .NET Standard 1.3 or .NET Standard 2.0 or .NET Framework 4.0.

Projects That Use Bogus
Featured In
Blog Posts
The Crypto Tip Jar!

Usage

The Great C# Example

public enum Gender
{
    Male,
    Female
}

//Set the randomizer seed if you wish to generate repeatable data sets.
Randomizer.Seed = new Random(8675309);

var fruit = new[] { "apple", "banana", "orange", "strawberry", "kiwi" };

var orderIds = 0;
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 => orderIds++)
    //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))
    //A nullable int? with 80% probability of being null.
    //The .OrNull extension is in the Bogus.Extensions namespace.
    .RuleFor(o => o.LotNumber, f => f.Random.Int(0, 100).OrNull(f, .8f));


var userIds = 0;
var testUsers = new Faker<User>()
    //Optional: Call for objects that have complex initialization
    .CustomInstantiator(f => new User(userIds++, f.Random.Replace("###-##-####")))

    //Use an enum outside scope.
    .RuleFor(u => u.Gender, f => f.PickRandom<Gender>())

    //Basic rules using built-in generators
    .RuleFor(u => u.FirstName, (f, u) => f.Name.FirstName(u.Gender))
    .RuleFor(u => u.LastName, (f, u) => f.Name.LastName(u.Gender))
    .RuleFor(u => u.Avatar, f => f.Internet.Avatar())
    .RuleFor(u => u.UserName, (f, u) => f.Internet.UserName(u.FirstName, u.LastName))
    .RuleFor(u => u.Email, (f, u) => f.Internet.Email(u.FirstName, u.LastName))
    .RuleFor(u => u.SomethingUnique, f => $"Value {f.UniqueIndex}")

    //Use a method outside scope.
    .RuleFor(u => u.CartId, f => Guid.NewGuid())
    //Compound property with context, use the first/last name properties
    .RuleFor(u => u.FullName, (f, u) => u.FirstName + " " + u.LastName)
    //And composability of a complex collection.
    .RuleFor(u => u.Orders, f => testOrders.Generate(3).ToList())
    //Optional: After all rules are applied finish with the following action
    .FinishWith((f, u) =>
        {
            Console.WriteLine("User Created! Id={0}", u.Id);
        });

var user = testUsers.Generate();
Console.WriteLine(user.DumpAsJson());

/* OUTPUT:
User Created! Id=0
 *
{
  "Id": 0,
  "FirstName": "Audrey",
  "LastName": "Spencer",
  "FullName": "Audrey Spencer",
  "UserName": "Audrey_Spencer72",
  "Email": "[email protected]",
  "Avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/itstotallyamy/128.jpg",
  "CartId": "863f9462-5b88-471f-b833-991d68db8c93",
  "SSN": "923-88-4231",
  "Gender": 0,
  "Orders": [
    {
      "OrderId": 0,
      "Item": "orange",
      "Quantity": 8
    },
    {
      "OrderId": 1,
      "Item": "banana",
      "Quantity": 2
    },
    {
      "OrderId": 2,
      "Item": "kiwi",
      "Quantity": 9
    }
  ]
} */

More Examples!

Language Description
C# Full working example of 'The Great C# Example'
C# Using Bogus and EF Core to a seed database
C# Extending Bogus with custom APIs and data
F# Using Bogus with F#
VB.NET Using Bogus with VB.NET

Locales

Since we're a port of faker.js, we support a whole bunch of different locales. Here's an example in Korean:

[Test]
public void With_Korean_Locale()
{
    var lorem = new Bogus.DataSets.Lorem(locale: "ko");
    Console.WriteLine(lorem.Sentence(5));
}

/* κ΅­κ°€λŠ” λ¬΄μƒμœΌλ‘œ ν–‰μœ„λ‘œ 의무λ₯Ό κ΅¬μ„±ν•˜μ§€ μ‹ μ²΄μ˜ μ²˜λ²Œλ°›μ§€ μ˜ˆμˆ κ°€μ˜ κ²½μš°μ™€ */

Bogus supports the following locales:

Locale Code Language Locale Code Language
af_ZA Afrikaans fr_CH French (Switzerland)
ar Arabic ge Georgian
az Azerbaijani hr Hrvatski
cz Czech id_ID Indonesia
de German it Italian
de_AT German (Austria) ja Japanese
de_CH German (Switzerland) ko Korean
el Greek lv Latvian
en English nb_NO Norwegian
en_AU English (Australia) ne Nepalese
en_AU_ocker English (Australia Ocker) nl Dutch
en_BORK English (Bork) nl_BE Dutch (Belgium)
en_CA English (Canada) pl Polish
en_GB English (Great Britain) pt_BR Portuguese (Brazil)
en_IE English (Ireland) pt_PT Portuguese (Portugal)
en_IND English (India) ro Romanian
en_NG Nigeria (English) ru Russian
en_US English (United States) sk Slovakian
en_ZA English (South Africa) sv Swedish
es Spanish tr Turkish
es_MX Spanish (Mexico) uk Ukrainian
fa Farsi vi Vietnamese
fi Finnish zh_CN Chinese
fr French zh_TW Chinese (Taiwan)
fr_CA French (Canada) zu_ZA Zulu (South Africa)

Note: Some locales may not have a complete data set. For example, zh_CN does not have a lorem data set, but ko has a lorem data set. Bogus will default to en if a locale-specific data set is not found. To further illustrate the previous example, the missing zh_CN:lorem data set will default to the en:lorem data set.

If you'd like to help contribute new locales or update existing ones please see our Creating Locales wiki page for more info.

Without Fluent Syntax

You can use Bogus without a fluent setup. The examples below highlight three alternative ways to use Bogus without a fluent syntax setup.

  • Using the Faker facade.
  • Using DataSets directly.
  • Using Faker<T> inheritance.

Using the Faker facade:

public void Using_The_Faker_Facade()
{
   var faker = new Faker("en");
   var o = new Order()
       {
           OrderId = faker.Random.Number(1, 100),
           Item = faker.Lorem.Sentence(),
           Quantity = faker.Random.Number(1, 10)
       };
   o.Dump();
}

Using DataSets directly:

public void Using_DataSets_Directly()
{
   var random = new Bogus.Randomizer();
   var lorem = new Bogus.DataSets.Lorem("en");
   var o = new Order()
       {
           OrderId = random.Number(1, 100),
           Item = lorem.Sentence(),
           Quantity = random.Number(1, 10)
       };
   o.Dump();
}

Using Faker<T> inheritance:

public class OrderFaker : Faker<Order> {
   public OrderFaker() {
      RuleFor(o => o.OrderId, f => f.Random.Number(1, 100));
      RuleFor(o => o.Item, f => f.Lorem.Sentence());
      RuleFor(o => o.Quantity, f => f.Random.Number(1, 10));
   }
}

public void Using_FakerT_Inheritance()
{
   var orderFaker = new OrderFaker();
   var o = orderFaker.Generate();
   o.Dump();
}

In the examples above, all three alternative styles of using Bogus produce the same Order result:

{
  "OrderId": 61,
  "Item": "vel est ipsa",
  "Quantity": 7
}

Bogus API Support

  • Address
    • ZipCode - Get a zipcode.
    • City - Get a city name.
    • StreetAddress - Get a street address.
    • CityPrefix - Get a city prefix.
    • CitySuffix - Get a city suffix.
    • StreetName - Get a street name.
    • BuildingNumber - Get a building number.
    • StreetSuffix - Get a street suffix.
    • SecondaryAddress - Get a secondary address like 'Apt. 2' or 'Suite 321'.
    • County - Get a county.
    • Country - Get a country.
    • FullAddress - Get a full address like Street, City, Country.
    • CountryCode - Get a random ISO 3166-1 country code.
    • State - Get a random state state.
    • StateAbbr - Get a state abbreviation.
    • Latitude - Get a Latitude.
    • Longitude - Get a Longitude.
    • Direction - Generates a cardinal or ordinal direction. IE: Northwest, South, SW, E.
    • CardinalDirection - Generates a cardinal direction. IE: North, South, E, W.
    • OrdinalDirection - Generates an ordinal direction. IE: Northwest, Southeast, SW, NE.
  • Commerce
    • Department - Get a random commerce department.
    • Price - Get a random product price.
    • Categories - Get random product categories.
    • ProductName - Get a random product name.
    • Color - Get a random color.
    • Product - Get a random product.
    • ProductAdjective - Random product adjective.
    • ProductMaterial - Random product material.
    • Ean8 - Get a random EAN-8 barcode number.
    • Ean13 - Get a random EAN-13 barcode number.
  • Company
    • CompanySuffix - Get a company suffix. "Inc" and "LLC" etc.
    • CompanyName - Get a company name.
    • CatchPhrase - Get a company catch phrase.
    • Bs - Get a company BS phrase.
  • Database
    • Column - Generates a column name.
    • Type - Generates a column type.
    • Collation - Generates a collation.
    • Engine - Generates a storage engine.
  • Date
    • Past - Get a DateTime in the past between refDate and yearsToGoBack.
    • PastOffset - Get a DateTimeOffset in the past between refDate and yearsToGoBack.
    • Soon - Get a DateTime that will happen soon.
    • SoonOffset - Get a DateTimeOffset that will happen soon.
    • Future - Get a DateTime in the future between refDate and yearsToGoForward.
    • FutureOffset - Get a DateTimeOffset in the future between refDate and yearsToGoForward.
    • Between - Get a random DateTime between start and end.
    • BetweenOffset - Get a random DateTimeOffset between start and end.
    • Recent - Get a random DateTime within the last few days.
    • RecentOffset - Get a random DateTimeOffset within the last few days.
    • Timespan - Get a random TimeSpan.
    • Month - Get a random month.
    • Weekday - Get a random weekday.
  • Finance
    • Account - Get an account number. Default length is 8 digits.
    • AccountName - Get an account name. Like "savings", "checking", "Home Loan" etc..
    • Amount - Get a random amount. Default 0 - 1000.
    • TransactionType - Get a transaction type: "deposit", "withdrawal", "payment", or "invoice".
    • Currency - Get a random currency.
    • CreditCardNumber - Generate a random credit card number with valid Luhn checksum.
    • CreditCardCvv - Generate a credit card CVV.
    • BitcoinAddress - Generates a random Bitcoin address.
    • EthereumAddress - Generate a random Ethereum address.
    • RoutingNumber - Generates an ABA routing number with valid check digit.
    • Bic - Generates Bank Identifier Code (BIC) code.
    • Iban - Generates an International Bank Account Number (IBAN).
  • Hacker
    • Abbreviation - Returns an abbreviation.
    • Adjective - Returns a adjective.
    • Noun - Returns a noun.
    • Verb - Returns a verb.
    • IngVerb - Returns a verb ending with -ing.
    • Phrase - Returns a phrase.
  • Images
    • DataUri - Get a SVG data URI image with a specific width and height.
    • PicsumUrl - Get an image from the https://picsum.photos service.
    • PlaceholderUrl - Get an image from https://placeholder.com service.
    • LoremFlickrUrl - Get an image from https://loremflickr.com service.
    • LoremPixelUrl - Creates an image URL with http://lorempixel.com. Note: This service is slow. Consider using PicsumUrl() as a faster alternative.
      • Abstract - Gets an abstract looking image.
      • Animals - Gets an image of an animal.
      • Business - Gets a business looking image.
      • Cats - Gets a picture of a cat.
      • City - Gets a city looking image.
      • Food - Gets an image of food.
      • Nightlife - Gets an image with city looking nightlife.
      • Fashion - Gets an image in the fashion category.
      • People - Gets an image of humans.
      • Nature - Gets an image of nature.
      • Sports - Gets an image related to sports.
      • Technics - Get a technology related image.
      • Transport - Get a transportation related image.
  • Internet
    • Avatar - Generates a legit Internet URL avatar from twitter accounts.
    • Email - Generates an email address.
    • ExampleEmail - Generates an example email with @example.com.
    • UserName - Generates user names.
    • UserNameUnicode - Generates a user name preserving Unicode characters.
    • DomainName - Generates a random domain name.
    • DomainWord - Generates a domain word used for domain names.
    • DomainSuffix - Generates a domain name suffix like .com, .net, .org
    • Ip - Gets a random IPv4 address string.
    • Port - Generates a random port number.
    • IpAddress - Gets a random IPv4 IPAddress type.
    • IpEndPoint - Gets a random IPv4 IPEndPoint.
    • Ipv6 - Generates a random IPv6 address string.
    • Ipv6Address - Generate a random IPv6 IPAddress type.
    • Ipv6EndPoint - Gets a random IPv6 IPEndPoint.
    • UserAgent - Generates a random user agent.
    • Mac - Gets a random mac address.
    • Password - Generates a random password.
    • Color - Gets a random aesthetically pleasing color near the base RGB. See here.
    • Protocol - Returns a random protocol. HTTP or HTTPS.
    • Url - Generates a random URL.
    • UrlWithPath - Get an absolute URL with random path.
    • UrlRootedPath - Get a rooted URL path like: /foo/bar. Optionally with file extension.
  • Lorem
    • Word - Get a random lorem word.
    • Words - Get an array of random lorem words.
    • Letter - Get a character letter.
    • Sentence - Get a random sentence of specific number of words.
    • Sentences - Get some sentences.
    • Paragraph - Get a paragraph.
    • Paragraphs - Get a specified number of paragraphs.
    • Text - Get random text on a random lorem methods.
    • Lines - Get lines of lorem.
    • Slug - Slugify lorem words.
  • Name
    • FirstName - Get a first name. Getting a gender specific name is only supported on locales that support it.
    • LastName - Get a last name. Getting a gender specific name is only supported on locales that support it.
    • FullName - Get a full name, concatenation of calling FirstName and LastName.
    • Prefix - Gets a random prefix for a name.
    • Suffix - Gets a random suffix for a name.
    • FindName - Gets a full name.
    • JobTitle - Gets a random job title.
    • JobDescriptor - Get a job description.
    • JobArea - Get a job area expertise.
    • JobType - Get a type of job.
  • Phone
    • PhoneNumber - Get a phone number.
    • PhoneNumberFormat - Gets a phone number based on the locale's phone_number.formats[] array index.
  • Rant
    • Review - Generates a random user review.
    • Reviews - Generate an array of random reviews.
  • System
    • FileName - Get a random file name.
    • DirectoryPath - Get a random directory path (Unix).
    • FilePath - Get a random file path (Unix).
    • CommonFileName - Generates a random file name with a common file extension.
    • MimeType - Get a random mime type.
    • CommonFileType - Returns a commonly used file type.
    • CommonFileExt - Returns a commonly used file extension.
    • FileType - Returns any file type available as mime-type.
    • FileExt - Gets a random extension for the given mime type.
    • Semver - Get a random semver version string.
    • Version - Get a random Version.
    • Exception - Get a random Exception with a fake stack trace.
    • AndroidId - Get a random GCM registration ID.
    • ApplePushToken - Get a random Apple Push Token.
    • BlackBerryPin - Get a random BlackBerry Device PIN.
  • Vehicle
    • Vin - Generate a vehicle identification number (VIN).
    • Manufacturer - Get a vehicle manufacture name. IE: Toyota, Ford, Porsche.
    • Model - Get a vehicle model. IE: Camry, Civic, Accord.
    • Type - Get a vehicle type. IE: Minivan, SUV, Sedan.
    • Fuel - Get a vehicle fuel type. IE: Electric, Gasoline, Diesel.
  • Random/Randomizer
    • Number - Get an int from 0 to max.
    • Digits - Get a random sequence of digits.
    • Even - Returns a random even number.
    • Odd - Returns a random odd number.
    • Double - Get a random double, between 0.0 and 1.0.
    • Decimal - Get a random decimal, between 0.0 and 1.0.
    • Float - Get a random float, between 0.0 and 1.0.
    • Byte - Generate a random byte between 0 and 255.
    • Bytes - Get a random sequence of bytes.
    • SByte - Generate a random sbyte between -128 and 127.
    • Int - Generate a random int between MinValue and MaxValue.
    • UInt - Generate a random uint between MinValue and MaxValue.
    • ULong - Generate a random ulong between MinValue and MaxValue.
    • Long - Generate a random long between MinValue and MaxValue.
    • Short - Generate a random short between MinValue and MaxValue.
    • UShort - Generate a random ushort between MinValue and MaxValue.
    • Char - Generate a random char between MinValue and MaxValue.
    • Chars - Generate a random chars between MinValue and MaxValue.
    • String - Get a string of characters of a specific length.
    • String2 - Get a string of characters with a specific length drawing characters from chars.
    • Hash - Return a random hex hash. Default 40 characters, aka SHA-1.
    • Bool - Get a random boolean.
    • ArrayElement<T> - Get a random array element.
    • ArrayElement - Get a random array element.
    • ArrayElements<T> - Get a random subset of an array.
    • ListItem<T> - Get a random list item.
    • ListItems<T> - Get a random subset of a List.
    • CollectionItem<T> - Get a random collection item.
    • ReplaceNumbers - Replaces symbols with numbers.
    • ReplaceSymbols - Replaces each character instance in a string.
    • Replace - Replaces symbols with numbers and letters. # = number, ? = letter, * = number or letter.
    • ClampString - Clamps the length of a string between min and max characters.
    • Enum<T> - Picks a random Enum of T. Works only with Enums.
    • Shuffle<T> - Shuffles an IEnumerable source.
    • Word - Returns a single word or phrase in English.
    • Words - Gets some random words and phrases in English.
    • WordsArray - Get a range of words in an array (English).
    • Guid - Get a random GUID.
    • Uuid - Get a random GUID. Alias for Randomizer.Guid().
    • RandomLocale - Returns a random locale.
    • AlphaNumeric - Returns a random set of alpha numeric characters 0-9, a-z.
    • Hexadecimal - Generates a random hexadecimal string.
    • WeightedRandom<T> - Returns a selection of T[] based on a weighted distribution of probability.

API Extension Methods

  • using Bogus.Extensions.Brazil;
    • Bogus.Person.Cpf() - Cadastro de Pessoas FΓ­sicas
    • Bogus.DataSets.Company.Cnpj() - Cadastro Nacional da Pessoa JurΓ­dica
  • using Bogus.Extensions.Canada;
    • Bogus.Person.Sin() - Social Insurance Number for Canada
  • using Bogus.Extensions.Denmark;
    • Bogus.Person.Cpr() - Danish Personal Identification number
  • using Bogus.Extensions.Finland;
    • Bogus.Person.Henkilotunnus() - Finnish HenkilΓΆtunnus
  • using Bogus.Extensions.Italy;
    • Bogus.Person.CodiceFiscale() - Codice Fiscale
    • Bogus.DataSets.Finance.CodiceFiscale() - Codice Fiscale
  • using Bogus.Extensions.Norway;
    • Bogus.Person.Fodselsnummer() - Norwegian national identity number
  • using Bogus.Extensions.Poland;
    • Bogus.Person.Pesel() - Number of Powszechny Elektroniczny System Ewidencji LudnoΕ›ci (PESEL)
    • Bogus.DataSets.Company.Nip() - Numer identyfikacji podatkowej (NIP)
    • Bogus.DataSets.Company.Regon() - Number of Rejestr Gospodarki Narodowej (REGON)
  • using Bogus.Extensions.Portugal;
    • Bogus.Person.Nif() - NΓΊmero de Identificação Fiscal (NIF)
    • Bogus.DataSets.Company.Nipc() - NΓΊmero de Identificação de Pessoa Colectiva (NIPC)
  • using Bogus.Extensions.Romania;
    • Bogus.Person.Cnp() - Romanian Personal Identification number (CNP)
  • using Bogus.Extensions.Sweden;
    • Bogus.Person.Personnummer() - Swedish national identity number
    • Bogus.Person.Samordningsnummer() - Swedish coordination number
  • using Bogus.Extensions.UnitedKingdom;
    • Bogus.DataSets.Vehicle.GbRegistrationPlate() - GB Vehicle Registration Plate
    • Bogus.DataSets.Finance.SortCode() - Banking Sort Code
    • Bogus.DataSets.Finance.Nino() - National Insurance Number
    • Bogus.DataSets.Finance.VatNumber() - Generates a UK compatible VAT registration number
    • Bogus.DataSets.Address.CountryOfUnitedKingdom() - Country of the United Kingdom
  • using Bogus.Extensions.UnitedStates;
    • Bogus.Person.Ssn() - Social Security Number
    • Bogus.DataSets.Company.Ein() - Employer Identification Number
  • using Bogus.Distributions.Gaussian;
    • Randomizer.GaussianInt() - Generate an int based on a specific normal distribution.
    • Randomizer.GaussianFloat() - Generate a float based on a specific normal distribution.
    • Randomizer.GaussianDouble() - Generate a double based on a specific normal distribution.
    • Randomizer.GaussianDecimal() - Generate a decimal based on a specific normal distribution.

Amazing Community Extensions

  • AutoBogus (NuGet Package) by @nickdodd79 - Extends Bogus by adding automatic .RuleFor() creation and population capabilities.
  • NaughtyStrings.Bogus (NuGet Package) by @SimonCropp - Extends Bogus with list of naughty strings which have a high probability of causing issues when used as user-input data. Examples:
    • .SQLInjection() - Strings which can cause a SQL injection if inputs are not sanitized.
    • .ScriptInjection() - Strings which attempt to invoke a benign script injection; shows vulnerability to XSS.
    • .iOSVulnerabilities() - Strings which crashed iMessage in various versions of iOS.
    • .KnownCVEsandVulnerabilities() - Strings that test for known vulnerabilities.
    • .ServerCodeInjection() - Strings which can cause user to run code on server as a privileged user.
    • and more!
  • WaffleGenerator.Bogus (NuGet Package) by @SimonCropp - The Waffle Generator produces of text which, on first glance, looks like real, ponderous, prose; replete with clichΓ©s.
  • NodaTime.Bogus (NuGet Package) by @SimonCropp - Adds support for NodaTime to Bogus.
  • CountryData.Bogus (NuGet Package) by @SimonCropp - Wrapper around GeoNames Data. Examples:
    • .Country().Name() - Random country name.
    • .Country().CurrencyCode() - Random currency code.
    • .Australia().Capital() - Country capital.
    • .Country().Iceland().PostCode() - Random country post code.
  • AustralianElectorates.Bogus (NuGet Package) by @SimonCropp - Wrapper around Australian Electoral Commission (AEC) data (https://www.aec.gov.au/). Examples:
    • .AustralianElectorates().Electorate() - Random electorate.
    • .AustralianElectorates().Name() - Random electorate name.
    • .AustralianElectorates().CurrentMember() - Random current electorate member for parliament.
    • .AustralianElectorates().CurrentMemberName() - Random name of current a electorate member for parliament.
    • .AustralianElectorates().Member() - Random electorate member for parliament.
    • .AustralianElectorates().MemberName() - Random name of a electorate member for parliament.

Bogus Premium Extensions!

Bogus Premium [Purchase Now!] by @bchavez
You can help support the Bogus open source project by purchasing a Bogus Premium license! With an active premium license you'll be supporting this cool open-source project. You'll also gain new superpowers that extended Bogus with new features and exclusive data sets! Check 'em out below!

  • Premium: Bogus.Tools.Analyzer (NuGet Package) - Save time using this handy Roslyn analyzer to generate and detect missing .RuleFor() rules at development & compile time! This tool is included with the Bogus Premium license!
  • Premium: Bogus.Locations (NuGet Package) - A dataset that contains real geographical information for places and things. Create fake GPS points and paths. Helpful for creating geodesic data for location-based aware apps.
    • Location
      • Altitude - Generate a random altitude, in meters. Default max height is 8848m (Mount Everest). Heights are always positive.
      • AreaCircle - Get a latitude and longitude within a specific radius in meters.
      • Depth - Generate a random depth, in meters. Default max depth is -10994m (Mariana Trench). Depths are always negative.
      • Geohash - Generates a random Geohash. See.
  • Premium: Bogus.Healthcare (NuGet Package) - A data set for the Healthcare industry. Generate fake medical records, injuries, diagnosis, drugs, dosages, human anatomy, and ICD-9 medical codes. Especially helpful in HIPAA regulated environments!
    • Drugs
      • Administration - Get how a drug should be administered. IE: oral, nasal, injection.
      • Dosage - Get a drug dosage with MG units
      • DosageAmount - Get a drug dosage.
      • DosageForm - Get the form of a drug. IE: tablet, capsule, gel.
      • Ingredient - Get a drug ingredient. IE: folic acid, magnesium hydroxide, ibuprofen.
      • Vitamin - Get a random vitamin.
    • Human
      • BloodType - Get a random blood type. Ex: A+, OB
      • BodyPartExternal - Get an external body part name. IE: Head, Arm, Leg.
      • BodyPartInternal - Get an internal body part name. IE: Bladder, Lung, Heart.
      • BodyRegion - Get a human body region. IE: Head and Neck, Thorax.
      • BodySystem - Get a human body system. IE: Digestive, Nervous, Circulatory.
      • Diagnosis - Shortcut to Icd9.DiagnosisLongDescription".
      • InfectiousDisease - Get an infectious disease. IE: Chickenpox, Polio, Zika Fever.
      • Pain - Get a human pain. Ex: Chest pain, Headache, Toothache.
      • Plasma - Get a random plasma type. Ex: O, A, B, AB
      • Procedure - Shortcut to Icd9.ProcedureLongDescription.
    • Icd9
      • DiagnosisCode - Get a ICD9 diagnosis code.
      • DiagnosisEntry - Get a medical diagnosis.
      • DiagnosisLongDescription - Get a medical diagnosis description. IE: Meningitis due to coxsackie virus.
      • DiagnosisShortDescription - Get a short description of a medical diagnosis.
      • ProcedureCode - Get a ICD9 procedure code.
      • ProcedureEntry - Get a medical procedure.
      • ProcedureLongDescription - Get a medical procedure description.
      • ProcedureShortDescription - Get a short description of a medical procedure.
    • Icd10
      • DiagnosisCode - Get a ICD10 diagnosis code.
      • DiagnosisEntry - Get a medical diagnosis.
      • DiagnosisLongDescription - Get a medical diagnosis description. IE: Meningitis due to coxsackie virus.
      • DiagnosisShortDescription - Get a short description of a medical diagnosis.
      • ProcedureCode - Get a ICD10 procedure code.
      • ProcedureEntry - Get a medical procedure.
      • ProcedureLongDescription - Get a medical procedure description.
      • ProcedureShortDescription - Get a short description of a medical procedure.
    • Medical
      • Hospital - Get a random hospital.
      • HospitalCity - Get a hospital city.
      • HospitalName - Get a random hospital name. IE: UCLA Medical Center
      • HospitalState - Get a hospital state.
      • HospitalStreetAddress - Get a hospital street address.
      • HospitalZipCode - Get a hospital ZipCode.
      • Phrase - Get a random medical phrase.
      • Word - Get a medical word.
  • Premium: Bogus.Hollywood (NuGet Package)- A dataset for the Entertainment industry.
    • Movies
      • ActorName - Get a famous actor. IE: Keanu Reeves, Liam Neeson, and Natalie Portman.
      • MovieCollection - Get a random movie collection. IE: Star Wars Collection, Indiana Jones Collection.
      • MovieOverview - Get a random movie overview
      • MovieReleaseDate - Get a random movie release date.
      • MovieTagline - Get a random movie tagline.
      • MovieTitle - Get a random movie title
      • Production - Get a production company.
    • Tv
      • ActorName - Get a famous actor. IE: Keanu Reeves, Liam Neeson, and Natalie Portman.
      • Network - Get a random TV network. IE: BBC, ABC, NBC, FOX.
      • Production - Get a production company
      • Series - Get a name of a TV series. IE: Rick and Morty, Silicon Valley, The Walking Dead
  • Premium: Bogus.Text (NuGet Package) - A dataset that contains historical texts in the public domain. Create fake sentences from famous speeches, classic books, and law
    • Literature
      • CommonSense - Text from "Common Sense, by Thomas Paine (1776)"
      • JfkSpeech - Text from "JFK's Inaugural Address"
      • Knowledge - Text from "A Treatise Concerning the Principles of Human knowledge, by George Berkeley (1710)"

Helper Methods

The features shown below come standard with the Bogus NuGet package.

Person

If you want to generate a Person with context relevant properties like an email that looks like it belongs to someone with the same first/last name, create a person!

[Test]
public void Create_Context_Related_Person()
{
    var person = new Bogus.Person();

    person.Dump();
}

/* OUTPUT:
{
  "FirstName": "Lee",
  "LastName": "Brown",
  "UserName": "Lee_Brown3",
  "Avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/ccinojasso1/128.jpg",
  "Email": "[email protected]",
  "DateOfBirth": "1984-01-16T21:31:27.87666",
  "Address": {
    "Street": "2552 Bernard Rapid",
    "Suite": "Suite 199",
    "City": "New Haskell side",
    "ZipCode": "78425-0411",
    "Geo": {
      "Lat": -35.8154,
      "Lng": -140.2044
    }
  },
  "Phone": "1-500-790-8836 x5069",
  "Website": "javier.biz",
  "Company": {
    "Name": "Kuphal and Sons",
    "CatchPhrase": "Organic even-keeled monitoring",
    "Bs": "open-source brand e-business"
  }
} */

Replace

Replace a formatted string with random numbers #, letters ?, or * random number or letter:

[Test]
public void Create_an_SSN()
{
    var ssn = new Bogus.Randomizer().Replace("###-##-####");
    ssn.Dump();

    var code = new Randomizer().Replace("##? ??? ####");
    code.Dump();

    var serial = new Randomizer().Replace("**-****");
    serial.Dump();
}
/* OUTPUT:
"618-19-3064"
"39E SPC 0790"
"L3-J9N5"
*/

Parse Handlebars

You can also parse strings in the following format:

[Test]
public void Handlebar()
{
    var faker = new Faker();
    var randomName = faker.Parse("{{name.lastName}}, {{name.firstName}} {{name.suffix}}");
    randomName.Dump();
}

/* OUTPUT:
"Roob, Michale PhD"
*/

The name of a dataset is determined using DataCategory attribute or class name otherwise. (i.e PhoneNumber dataset in handlebars expression should be named as phone_number)

You can pass parameters to methods using braces:

[Test]
public void HandlebarWithParameters()
{
    var faker = new Faker();
    var randomName = faker.Parse("{{name.firstname(Female)}}, {{name.firstname(Male)}}");
    randomName.Dump();
}

/* OUTPUT:
"Lindsay, Jonathan"
*/

Implicit and Explicit Type Conversion

You can also use implicit type conversion to make your code look cleaner without having to explicitly call Faker<T>.Generate().

var orderFaker = new Faker<Order>()
                     .RuleFor(o => o.OrderId, f => f.IndexVariable++)
                     .RuleFor(o => o.Item, f => f.Commerce.Product())
                     .RuleFor(o => o.Quantity, f => f.Random.Number(1,3));

Order testOrder1 = orderFaker;
Order testOrder2 = orderFaker;
testOrder1.Dump();
testOrder2.Dump();

/* OUTPUT:
{
  "OrderId": 0,
  "Item": "Computer",
  "Quantity": 2
}
{
  "OrderId": 1,
  "Item": "Tuna",
  "Quantity": 3
}
*/

//Explicit works too!
var anotherOrder = (Order)orderFaker;

Bulk Rules

Sometimes writing .RuleFor(x => x.Prop, ...) can get repetitive, use the .Rules((f, t) => {...}) shortcut to specify rules in bulk as shown below:

public void create_rules_for_an_object_the_easy_way()
{
    var faker = new Faker<Order>()
        .StrictMode(false)
        .Rules((f, o) =>
            {
                o.Quantity = f.Random.Number(1, 4);
                o.Item = f.Commerce.Product();
                o.OrderId = 25;
            });
    Order o = faker.Generate();
}

Note: When using the bulk .Rules(...) action, StrictMode cannot be set to true since individual properties of type T cannot be independently checked to ensure each property has a rule.

Using Enumerable.Range() and LINQ

The Enumerable.Range() and LINQ are a great supplement when creating data with Bogus. Here's how to generate a simple list of email addresses:

var faker = new Faker("en");

var emailList = Enumerable.Range(1, 5)
      .Select(_ => faker.Internet.Email())
      .ToList();

//OUTPUT:
Gustave83@hotmail.com    
Evie33@gmail.com 
Abby_Wilkinson@yahoo.com 
Cecilia.Hahn@yahoo.com   
Jasen.Waelchi85@gmail.com     

Advanced Topics, Guidance, and Best Practices

Determinism

Determinism is a first class concept in Bogus. Bogus goes to great lengths so developers can generate the same sequence of data over multiple program executions. Bogus has two strategies of setting up deterministic behavior:

  1. Global Seed determinism through the Randomizer.Seed global static property.
    Pros: Easy to get deterministic data setup quickly.
    Cons: Code changes can impact other data values. Not so good for unit tests.

  2. Local Seed determinism through instance properties and methods. Specifically,

    • The Faker<T>.UseSeed(int) method.
    • The .Random property on the Faker facade and DataSets.

    Pros: Code changes can be isolated with minimal impact on determinism. Good for unit tests.
    Cons: Requires some forethought in design.

When Local Seed determinism is used to set a seed value, the global static source of randomness is ignored. This has some interesting implications as described below.

Using Global Seed determinism

The easiest way to get deterministic data values over multiple executions of a program is to set the Randomizer.Seed property as demonstrated below:

Randomizer.Seed = new Random(1338);
var orderIds = 0;
var orderFaker = new Faker<Order>()
    .RuleFor(o => o.OrderId, f => orderIds++)
    .RuleFor(o => o.Item, f => f.Commerce.Product())
    .RuleFor(o => o.Quantity, f => f.Random.Number(1, 5));

orderFaker.Generate(5).Dump();
OrderId Item Quantity
0 Fish 3
1 Chair 1
2 Gloves 5
3 Shirt 4
4 Hat 4

Re-running the code above with 1338 as a global static seed value will produce the same table of data over and over again.

Next, add a new Description property to the Order class along with a new .RuleFor(o => o.Description, ..) rule and see the data changes:

Randomizer.Seed = new Random(1338);
var orderIds = 0;
var orderFaker = new Faker<Order>()
    .RuleFor(o => o.OrderId, f => orderIds++)
    .RuleFor(o => o.Item, f => f.Commerce.Product())
    .RuleFor(o => o.Description, f => f.Commerce.ProductAdjective()) //New Rule
    .RuleFor(o => o.Quantity, f => f.Random.Number(1, 5));

orderFaker.Generate(5).Dump();
OrderId Item Description Quantity
0 Fish Fantastic 🚩 1
1 🚩 Keyboard 🚩 Gorgeous 🚩 5
2 🚩 Shirt 🚩 Handcrafted 🚩 3
3 🚩 Tuna 🚩 Small 🚩 1
4 🚩 Table 🚩 Awesome 🚩 3

A couple of observations:

  • Order 0: Item value Fish remained the same.
  • Order 0: Quantity changed from 3 to 1.
  • Order 1: Item has changed from a Chair to a Keyboard.

In fact, every data value with a 🚩 icon has changed. This is due to the newly added property which has the effect of shifting the entire global static pseudo-random sequence off by +1. This rippling effect can be a problem if unit tests are expecting data values to remain the same. The following section below shows how we can improve the situation.

Using Local Seed determinism

Making use of the Faker<T>.UseSeed(int) method can help limit the impact of POCO schema changes on deterministic data values that span across an entire run. Consider the following code that uses a seed value for each instance of a POCO object:

var orderIds = 0;
var orderFaker = new Faker<Order>()
    .RuleFor(o => o.OrderId, f => orderIds++)
    .RuleFor(o => o.Item, f => f.Commerce.Product())
    .RuleFor(o => o.Quantity, f => f.Random.Number(1, 5));
    
Order SeededOrder(int seed){
   return orderFaker.UseSeed(seed).Generate();
}

var orders = Enumerable.Range(1, 5)
   .Select(SeededOrder)
   .ToList();

orders.Dump();
OrderId Item Quantity
0 Bike 1
1 Cheese 3
2 Gloves 4
3 Bacon 5
4 Pants 2

Next, adding the Description property to the Order class and examining the output:

var orderIds = 0;
var orderFaker = new Faker<Order>()
    .RuleFor(o => o.OrderId, f => orderIds++)
    .RuleFor(o => o.Item, f => f.Commerce.Product())
    .RuleFor(o => o.Description, f => f.Commerce.ProductAdjective()) //New Rule
    .RuleFor(o => o.Quantity, f => f.Random.Number(1, 5));
    
Order SeededOrder(int seed){
   return orderFaker.UseSeed(seed).Generate();
}

var orders = Enumerable.Range(1,5)
   .Select(SeededOrder)
   .ToList();

orders.Dump();
OrderId Item Description Quantity
0 Bike Ergonomic 🚩 3
1 Cheese Fantastic 🚩 1
2 Gloves Handcrafted 🚩 5
3 Bacon Tasty 🚩 3
4 Pants Gorgeous 🚩 2

Progress! This time only the Quantity data values with the 🚩 icon have changed. The Item column remained the same before and after the new addition of the Description property.

We can further prevent the Quantity data values from changing by moving the RuleFor(o => o.Description,...) rule line to the end of the Faker<Order> declaration as shown below:

var orderIds = 0;
var orderFaker = new Faker<Order>()
    .RuleFor(o => o.OrderId, f => orderIds++)
    .RuleFor(o => o.Item, f => f.Commerce.Product())
    .RuleFor(o => o.Quantity, f => f.Random.Number(1, 5))
    .RuleFor(o => o.Description, f => f.Commerce.ProductAdjective()); //New Rule
    
Order MakeOrder(int seed){
   return orderFaker.UseSeed(seed).Generate();
}

var orders = Enumerable.Range(1,5)
   .Select(MakeOrder)
   .ToList();

orders.Dump();
OrderId Item Quantity Description
0 Bike 1 Practical
1 Cheese 3 Rustic
2 Gloves 4 Refined
3 Bacon 5 Awesome
4 Pants 2 Gorgeous

Much success! πŸ’― πŸŽ‰ The Item and Quantity values remain unchanged! The new Description property is added to the POCO object without any impact to other deterministic data values.

As a best practice, to achieve maximum deterministic behavior and unit test robustness with Bogus:

  • βœ”οΈ Add new RuleFor rules last in Faker<T> declarations.
  • βœ”οΈ Avoid changing existing rules.
  • βœ”οΈ Always use Faker<T>.UseSeed(int) to avoid using the global static seed as a source for randomness.
  • βœ”οΈ When possible assert that a value exists, not the literal value itself. In other words,
    // Don't do this:
    firstOrder.Item.Should().Be("Bike");
    
    // Instead, do this:
    firstOrder.Item.Should().NotBeNullOrWhiteSpace();

The Faker facade and individual DataSets can also be prepared to use local seeds as well. The following shows how to set up the Faker facade and DataSets to use local seeds:

var faker = new Faker("en")
                {
                   Random = new Randomizer(1338)
                };
var lorem = new Bogus.DataSets.Lorem("en"){
                   Random = new Randomizer(1338)
                };
faker.Lorem.Word().Dump();
lorem.Word().Dump();

//OUTPUT:
minus
minus

The .Random property can be set multiple times without any ill effects.

Versioning can effect determinism

Updating to new versions of Bogus on NuGet can effect determinism too. For example, when Bogus updates locales from faker.js or issues bug fixes, sometimes deterministic sequences can change. Changes to deterministic outputs are usually highlighted in the release notes. Changes to deterministic outputs is also considered a breaking change. Bogus generally follows semantic versioning rules. For example:

Version Description
Bogus v25.0.1 Initial version.
Bogus v25.0.2 No change to deterministic outputs or breaking changes. Possible bug fixes & improvements.
Bogus v26.0.1 Deterministic outputs may have changed or may include other breaking changes.

As a general rule of thumb,

  • βœ”οΈ For maximum stability for unit tests, stay within the same major versions of Bogus.
  • βœ”οΈ For those wanting to stay up to date, assert that a value exists, not a literal value itself. In other words,
    // Don't do this:
    firstOrder.Item.Should().Be("Bike");
    
    // Instead, do this:
    firstOrder.Item.Should().NotBeNullOrWhiteSpace();

Deterministic Dates and Times

Bogus can generate deterministic dates and times. However, generating deterministic dates and times requires the following:

  1. Setting up a seed value.
  2. Setting up a time reference for your Faker object instance.

The following code shows how to setup deterministic dates and times:

// Faker[T]: Set a local seed and a time reference
var fakerT = new Faker<Order>()
                 .UseSeed(1338)
                 .UseDateTimeReference(DateTime.Parse("1/1/1980"))
                 .RuleFor(o => o.SoonValue,   f => f.Date.Soon())
                 .RuleFor(o => o.RecentValue, f => f.Date.Recent());
fakerT.Generate().Dump();
//  { "SoonValue":   "1980-01-01T17:33:05",
//    "RecentValue": "1979-12-31T14:07:31" }

// Faker: Set a local seed and a time reference
var faker = new Faker
   {
      Random = new Randomizer(1338),
      DateTimeReference = DateTime.Parse("1/1/1980")
   };
faker.Date.Soon();   // "1980-01-01T17:33:05"
faker.Date.Recent(); // "1979-12-31T14:07:31"

With a time reference set and a seed, dates and times should be deterministic across multiple runs of a program.

F# and VB.NET Examples

The Fabulous F# Examples

  • Using the Faker facade with immutable F# record types:
type Customer = { FirstName : string
                  LastName : string
                  Age : int
                  Title : string }

//The faker facade
let f = Faker();

let generator() = 
   { FirstName = f.Name.FirstName()
     LastName  = f.Name.LastName()
     Age       = f.Random.Number(18,60)
     Title     = f.Name.JobTitle() }
     
generator() |> Dump |> ignore

(* OUTPUT:
  FirstName = "Russell"
  LastName = "Nader"
  Age = 34
  Title = "Senior Web Officer"
*)
  • Using the Faker<T> class with immutable F# record types:
type Customer = { FirstName : string
                  LastName : string
                  Age : int
                  Title : string }

let customerFaker =
    Bogus
        .Faker<Customer>()
        .CustomInstantiator(fun f ->
             { FirstName = f.Name.FirstName()
               LastName  = f.Name.LastName()
               Age       = f.Random.Number(18,60)
               Title     = f.Name.JobTitle() })

customerFaker.Generate() |> Dump |> ignore

(* OUTPUT:
  FirstName = "Sasha"
  LastName = "Roberts"
  Age = 20;
  Title = "Internal Security Specialist"
*)
  • Using the Faker<T> class with mutable classes in F#:
open Bogus
type Customer() =
  member val FirstName = "" with get, set
  member val LastName = "" with get, set
  member val Age = 0 with get, set
  member val Title = "" with get, set

let faker = 
        Faker<Customer>()
          //Make a rule for each property
          .RuleFor( (fun c -> c.FirstName), fun (f:Faker) -> f.Name.FirstName() )
          .RuleFor( (fun c -> c.LastName), fun (f:Faker) -> f.Name.LastName() )

          //Or, alternatively, in bulk with .Rules()
          .Rules( fun f c -> 
                    c.Age <- f.Random.Int(18,35) 
                    c.Title <- f.Name.JobTitle() )
  
faker.Generate() |> Dump |> ignore

(* OUTPUT:
  FirstName: Jarrell
  LastName: Tremblay
  Age: 32
  Title: Senior Web Designer
*)

The Very Basic VB.NET Example

Imports Bogus

Public Class Customer
    Public Property FirstName() As String
    Public Property LastName() As String
    Public Property Age() As Integer
    Public Property Title() As String
End Class

Sub Main
    Dim faker As New Faker(Of Customer)
    
    '-- Make a rule for each property
    faker.RuleFor( Function(c) c.FirstName, Function(f) f.Name.FirstName) _
         .RuleFor( Function(c) c.LastName, Function(f) f.Name.LastName) _
         _
         .Rules( Sub(f, c)   '-- Or, alternatively, in bulk with .Rules() 
                   c.Age = f.Random.Int(18,35) 
                   c.Title = f.Name.JobTitle()
                 End Sub )
            
    faker.Generate.Dump
End Sub

' OUTPUT:
' FirstName: Jeremie 
' LastName: Mills 
' Age: 32 
' Title: Quality Supervisor 

Building From Source

The following section is only useful for people looking to contribute to Bogus or make custom modifications to Bogus. This section includes information about building Bogus from source code and is not required to operate or run Bogus in .NET applications.

The minimum requirements to build Bogus from source code are as follows:

Build Instructions

  • Download the source code.
  • Open command prompt and run build.cmd:
    • build restore - restores all project references.
    • build compile - the main dotnet build task.
    • build clean - cleans sources and files.
    • build zip - creates a nice zip file with debug and release binaries.
    • build pack - builds NuGet packages.
    • build test - runs all unit tests.

The following folders will be created depending on the build task executed:

  • \__compile - binary output folder for the compiler.
  • \__package - output folder for zip and NuGet packages.
  • \__test - test results folder.

Build Environment Variables

  • set FORCE_VERSION=1.2.3
    If FORCE_VERSION environment variable is set with a semantic version number (eg: x.y.z), the build tasks will use the FORCE_VERSION to produce builds with the exact version number. Useful for testing out-of-band custom builds. However, it is not possible to reproduce exact binary equivalents of released NuGet packages because packages release on NuGet contain assemblies that are digitally signed with assembly signing enabled. The public does not have access to the signing key.

Rebundling Locales

Re-bundling the latest locale data from faker.js requires the following software installed:

Steps to re-bundle locale data from faker.js:

  1. git clone https://github.com/bchavez/Bogus.git
  2. cd Bogus
  3. git submodule init
  4. git submodule update
  5. Ensure NodeJS and gulp are properly installed.
  6. cd Source\Builder
  7. npm install to install required dev dependencies.
  8. npx gulp importLocales to regenerate locales in Source\Bogus\data.
  9. Finally, run build.cmd.

License

Contributors

Created by Brian Chavez.

A big thanks to GitHub and all contributors:

bogus's People

Contributors

ahmetcanaydemir avatar bartdebever avatar bchavez avatar chuuddo avatar codersg avatar hjerpbakk avatar joelharkes avatar jvanderstad avatar logiclrd avatar m-clk avatar marky291 avatar maxyushchenko avatar mik1mak avatar mika-s avatar mitchman215 avatar mmosiur avatar mpdreamz avatar munroraymaker avatar nschoenberg avatar prasadtelkikar avatar quantumplation avatar rjcarneiro avatar rodrigo-web-developer avatar rowland-banks-abide avatar saiedbasha avatar salixzs avatar sander1095 avatar simoncropp avatar skwasjer avatar supix avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bogus's Issues

FinishWith for the whole generate set

I am happy to post this somewhere else if you have a uservoice or something. It would be nice if there was a way to do finishwith on a whole set. For instance, I want to generate a collection of objects and always have the first one set to primary.

Currently I have to do the following:

 public static Faker<x> GetBusinessEntityRules()
    {
      var rules = new Faker<x>()
          .RuleFor(o => o.Code, f => f.Random.AlphaNumeric(5))
          .RuleFor(o => o.Dba, f => BogusDataSets.Company.CompanyName())        

      return rules;
    }

     // Get x
      var z = BogusRules.GetBusinessEntityRules().Generate(5).ToList();

      // Set the first to primary
      z[0].Primary = true;

Instead it would nice to make the rule responsible for this:

 public static Faker<x> GetBusinessEntityRules()
    {
      var rules = new Faker<x>()
          .RuleFor(o => o.Code, f => f.Random.AlphaNumeric(5))
          .RuleFor(o => o.Dba, f => BogusDataSets.Company.CompanyName())        
         .FinishCollectionWith(list) {
.... list[0].Primary = true... etc.
}

      return rules;
    }

Integrating Bogus with FluentValidation's Rules

Hi! I see that Bogus is heavily inspired by FluentValidation's sintax. I wonder if it's possible to integrate Bogus directly wiht FluentValidation's rules and validators. I mean, if I already have an AbstractValidator, can I use Bogus to generate data respecting the rules/constraints of that validator? (This would spare so much time for anyone using FluentValidation and xUnit)

Get unique global values for child property

I have the following:

    Faker<ProductI18N> productsI18N = new Faker<FoodI18N>()
      .RuleFor(x => x.Name, y => $"{y.Lorem.Word()} {y.Hashids.Encode(y.IndexGlobal)}");

    List<Product> products = new Faker<Product>()
      .RuleFor(x => x.ProductsI18N, () => productsI18N.Generate(2).ToList())
      .RuleFor(x => x.IsApproved, x => x.Random.Bool())
      .Generate(2000).ToList();

Each ProductI18N should have an unique name that is why I added:

    $"{y.Lorem.Word()} {y.Hashids.Encode(y.IndexGlobal)}")

However I get duplicates ... Why? How to overcome this?

Make api application consistency ... So Locale would become Locale()

Hello,

I was checking the following:

.RuleFor(x => x.Locale, y => y.Address.Locale)
.RuleFor(x => x.Latitude, y => y.Address.Latitude())

I think that, for consistency, a method should always be used, e.g., Locale()

And this could be an extending point of Bogus ... For example:

public static Locale(this IValueResolver resolver) {

}

So all API options would be an extension of an "IValueResolver" ...

Having, for example, a Hacker property in Faker class seems kind of strange ... Maybe it should be an extension or maybe Faker could be a partial class to allow adding more properties as a way to extending it ... Well, not sure if this is the best option. Just an idea ...

Thanks,
Miguel

How generate list of string with Bogus library in C#?

I have a class :

public class Person
{
   public int Id {get; set;}
   public List<string> Phones {get; set;} // PROBLEM !!!
}

var Ids = 0;
var test = new Faker<Person>()
    .RuleFor(p => p.Id, f => Ids ++)
    .RuleFor(p => p.Phones , f => /*HOW ?????*/) // How can I return random list of PhoneNumbers ???

README Image docs inaccurate

README.md "Images" section is inaccurate:

  • The header (Images) implies that the faker accessor is called Images but it's actually Image
  • The list of options include ImageUrl which is actually a protected method

Strong Name

The assembly is missing a strong name at the moment, so it can't be used in assemblies that are themselves strong named.
All our assemblies have a strong name as company policy, so at the moment we always have to recompile and can't use the nuget package.

Define char quantity in random names

It would be very useful if we could insert a parameter to define a maximum and minimum quantity of characters in any object generated.
It would help many in running unit tests!

Thank you very much!
Nicola Picoli

Generate child entities with one culture each

Hello,

I am trying to generate localized data on an application so I have:

      Faker<EbookI18N> ebookI18Ns = new Faker<EbookI18N>()
        .RuleFor(x => x.LanguageCode, y => "en")
        .RuleFor(x => x.Description, y => y.Lorem.Paragraphs(1))
        .RuleFor(x => x.Title, y => y.Lorem.Sentence(4));

      List<Ebook> ebooks = new Faker<Ebook>()
        .RuleFor(x => x.Id, () => 0)            
        .RuleFor(x => x.EbookI18Ns, () => ebookI18Ns.Generate(2))
        .Generate(8).ToList();

The question is on the following line on ebook faker:

        .RuleFor(x => x.EbookI18Ns, () => ebookI18Ns.Generate(2))

How can I create two ebookI18Ns with one having LanguageCode="en" and the other with LanguageCode="pt" instead of the constant "en" value I have on ebookI18Ns?

The first thing I though was passing values to the Generate method. Something like:

        .RuleFor(x => x.EbookI18Ns, () => ebookI18Ns.Generate(2, new { LanguageCode = "something" }));

Any ideas?

Thank You,
Miguel

Suggestion: allow faker rules to be overridden

I think it would be useful to allow rules to be overridden on fakers. Currently there is an exception thrown when a rule has already been added for the property. If instead, the existing rule was replaced, you could very easily create test data builders like the following.

public class FakeCustomerBuilder
{
    private readonly Faker<Customer> _customerFaker;

    public FakeCustomerBuilder()
    {
        _customerFaker = new Faker<Customer>()
            .RuleFor(customer => customer.Forename, faker => faker.Name.FirstName())
            .RuleFor(customer => customer.Surname, faker => faker.Name.LastName());
    }

    public CustomerBuilder WithSurname(string surname)
    {
        _customerFaker.RuleFor(c => c.Surname, faker => surname);
        return this;
    }

    public Customer Build()
    {
        return _customerFaker.Generate();
    }
}

Create N time series

I have the following classes:

public class Measure {
  public Int32 Id { get; set; }
  public Int32 UserId { get; set; }
  public Int32 MeasureTypeId { get; set; }
  public DateTime Created { get; set;  }
  public Decimal Value { get; set; }
}

public class User {
  public Int32 Id { get; set; }
  public String Name { get; set; }
  public ICollection<Measure> Measures { get; set; }
}

The property MeasureTypeId can be a number between 1 to 4.

I am creating 20 random Users as follows:

    List<User> users = new Faker<User>()
      .RuleFor(x => x.Id, () => 0)
      .RuleFor(x => x.Name, y => y.Person.FirstName)
      .Generate(20).ToList();  

I need to create 4 lists of Measures (one for each MeasureTypeId 1 to 4) with 60 points:

  • The created date is incremented day by day starting on 1 Janurary 2017;
  • The value is a random between 10 to 20.

Basically, I need to create 4 time series (one for each MeasureTypeId) for each user.

I am able to generate One or Many Measure ... I am just not sure how to create such time series.

Is there a straight forward way with Bogus?

Feature: RuleFor Type

I have class with 50-100 properties. I would like something like

.RuleFor<int>(y => y.Random.Int(1, 100))
.RuleFor<double>(y => y.Random.Double())
.RuleFor(x=>x.SomeIntProperty, y=>y.Int(100,200))

or

.RuleFor(typeof(int), y => y.Random.Int(1, 100))

ability to set rules for types and override rule for specific property.

.Net CORE support?

I'm about to try it anyways, but figured I would ask so that it could be documented should any others happen by with the same question.

Generating a random time on a date?

Is there any way to extend the rule to get a recent date, such that you can also get a random time on the date?

Currently the time element always seems the time when object was generated. My rule looks like:

.RuleFor(m => m.Timestamp, m => m.Date.Recent(0))

I would like to be able to generate random times as well as dates.

Roadmap guide (need missing features)

Hi!

As Bogus is port of faker.js and provides outstanding close-to-real data generation possibilities, there are some features I would like to see in this library to make it even more usable.
What is approach in Bogus? Is it strictly following faker.js feature scope or can it develop something on its own, which is not found in faker.js?

I am currently missing

  • Use different locale for some functionality which is different from set for faker object.
var faker = new Faker<Person>("de")
    .RuleFor(p => p.LastNameNative, f => f.Name.LastName() // Generates German Lastname
    .RuleFor(p => p.LastNameTransliterated, f => f.Name.LastName("en"); // Takes English names (no ΓΆΓ€ etc. chars)
  • Getting LOREM strings of particular length, like to test storing string with maximum length in db field. f => f.Lorem.AsString(100) would return "Lorem ipsum..." as string with exactly 100 characters in length.
  • faker.js already have pull request to change Lorem.Words to return string (and not array), which is more consistent with the rest of methods.
  • Getting random alphabet letter f => f.Random.Letter would return any letter in alphabet randomly.
    This might require alphabet set in locale datasets (which is not found in faker.js yet), but at least getting random English alphabet letter would suffice initially.
  • Returning random element from Enum, but not default (value=0), like f => f.Random.Enum<MyEnum>(exceptDefault: true)Β­
  • Random.Replace() could have placeholder for "digit-or-letter"

Can be achieved with Random.Replace(), but better to have specific method for it.

  • Generating Bank IBAN account numbers which would pass validation.
  • Generating Bank SWIFT codes - valid for testing validators.
  • Generating fake person identity codes / social security numbers.

There are some ideas and needs - can they be added to Bogus, despite they are missing in faker.js?

Company Name appears twice in Readme

CompanyName - Get a company name
CompanyName - Get a company name. The format can use any name.* and company.* methods.

I would fix this but I don't know which is correct.

Create a well defined way to extend Bogus

Hello,

I think it would be really useful to have a common way to extend bogus. I am using:

public static String DummyImage(this Images images, Int32 width = 640, Int32 height = 480) {
  return $"https://placehold.it/{width}x{height}";
}

But I feel that extending Bogus is not very clear ... A common API for extending would be great.

BTW, Images return a URL but most of the cases what I need is a BYTE array of the image to save on da database filestream or on a folder. So I am using the following:

public static class HttpFileLoader {

  private static IDictionary<String, Byte[]> files = new Dictionary<String, Byte[]>();

  public static Byte[] Load(this String url) {
    return LoadAsync(url).Result;
  } 

  public async static Task<Byte[]> LoadAsync(this String url) {

    if (files.ContainsKey(url))
      return files[url];

      using (HttpClient client = new HttpClient()) { 
        Byte[] file = await client.GetByteArrayAsync(url);
        files.Add(url, file);
        return file;
      }          
  }
} 

Note: I am saving the URL and File on a dictionary for caching.
I think for dummy data that is enough ...

And I use it:

      List<File> files = new Faker<File>()
        .RuleFor(x => x.Id, y => 0)
        .RuleFor(x => x.Content, y => y.Image.DummyImage(80, 80).Load())

And now I got the Image content and not just an URL.
I am not sure if it makes sense to have this included on Bogus ...
Just explaining the way I am using it.

Thank You,
Miguel

Question about failing unit tests

Hi there,

in the locale files there is support for alternative combining of address strings. For example in the locale nl (Dutch) the cities can be combined using the following rules:

https://github.com/bchavez/Bogus/blob/master/Source/Bogus/data/nl.locale.json#L44

"city": [
        "#{Name.first_name}#{city_suffix}",
        "#{Name.last_name}#{city_suffix}",
        "#{city_prefix} #{Name.first_name}#{city_suffix}",
        "#{city_prefix} #{Name.last_name}#{city_suffix}"
      ]

Those rules are now hardcoded in https://github.com/bchavez/Bogus/blob/master/Source/Bogus/DataSets/Address.cs#L40

I have commited support for thore rules in the following commit:

JvanderStad@bfb57a0

However, some unittests are failing:

image
image

eg:

Expected string to be 
"1860 Bechtelar Rest" with a length of 19, but 
"60643 Oberbrunner Bypass" has a length of 24.

   at FluentAssertions.Execution.LateBoundTestFramework.Throw(String message) in z:\Builds\work\eed5b735bfe0fb8d\Shared\Execution\LateBoundTestFramework.cs:line 30
   at FluentAssertions.Execution.AssertionScope.FailWith(String message, Object[] args) in z:\Builds\work\eed5b735bfe0fb8d\FluentAssertions.Core\Execution\AssertionScope.cs:line 197
   at FluentAssertions.Primitives.StringEqualityValidator.ValidateAgainstLengthDifferences() in z:\Builds\work\eed5b735bfe0fb8d\FluentAssertions.Core\Primitives\StringEqualityValidator.cs:line 40
   at FluentAssertions.Primitives.StringValidator.Validate() in z:\Builds\work\eed5b735bfe0fb8d\FluentAssertions.Core\Primitives\StringValidator.cs:line 42
   at FluentAssertions.Primitives.StringAssertions.Be(String expected, String because, Object[] reasonArgs) in z:\Builds\work\eed5b735bfe0fb8d\FluentAssertions.Core\Primitives\StringAssertions.cs:line 40
   at Bogus.Tests.AddressTest.can_get_a_street_address() in c:\Workspace\Ontwikkeling\GitHub\Bogus\Source\Bogus.Tests\AddressTest.cs:line 40

As far as I understand this is how the unit tests in this project work:

The seed is predetermined and every Seed.Next() will return predictable results ( ❔ )

Because I have changed the the lookup of string values, the amount of calls to Seed.Next() has changed, as a result the unit tests are failing.

That's my assumption or am I missing something?

Random.Words() intermittent IndexOutOfRange failure

using Faker.Random.Words() sometimes fails due to the following exception:

System.IndexOutOfRangeException : Index was outside the bounds of the array.
  at Bogus.DataSets.Commerce.Department (Int32 max, Boolean returnMax) <0x404d82d0 + 0x000e6> in <filename unknown>:0 
  at Bogus.WordFunctions+<>c__DisplayClass1_0.<.cctor>b__0 () <0x404d8260 + 0x00028> in <filename unknown>:0 
  at Bogus.Randomizer.Word () <0x40480060 + 0x00047> in <filename unknown>:0 
  at Bogus.Randomizer.<Words>b__19_0 (Int32 f) <0x40480020 + 0x00014> in <filename unknown>:0 
  at System.Linq.Enumerable+WhereSelectEnumerableIterator`2[TSource,TResult].MoveNext () <0x4047fe00 + 0x000ef> in <filename unknown>:0 
  at System.Linq.Buffer`1[TElement]..ctor (IEnumerable`1 source) <0x40cff760 + 0x00209> in <filename unknown>:0 
  at System.Linq.Enumerable.ToArray[TSource] (IEnumerable`1 source) <0x40cff670 + 0x00058> in <filename unknown>:0 
  at Bogus.Randomizer.Words (Nullable`1 count) <0x4047f180 + 0x00124> in <filename unknown>:0 
  at ImsHealth.RollbarLoggingProvider.Tests.Generators.RandomLoggerName () <0x4047ee00 + 0x00037> in <filename unknown>:0 
...
  at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
  at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) <0x7f83877f38f0 + 0x000a3> in <filename unknown>:0 

Boolean does now get random?

Hello,

I just tried the following faker:

      List<Ebook> ebooks = new Faker<Ebook>()
        .RuleFor(x => x.Id, () => 0)
        .RuleFor(x => x.IsApproved, y => y.Random.Bool())
        .RuleFor(x => x.EbookI18Ns, () => ebookI18Ns.Generate(_languages.Count).ToList())
        .RuleFor(x => x.Updated, (y, x) => y.Date.Between(DateTime.Now.AddDays(-40), DateTime.Now.AddDays(-20)))
        .Generate(20).ToList();

But the IsApproved is false in all items.

How can I get items with true or false in IsApproved?

Thank You,
Miguel

Thread Safety in Unit Tests

User report from @PureKrome via twitter:

Bogus' Faker RuleFor actions isn't thread safe. Some test runners use multiple threads to run tests. So, some code like:

var userIds = 0;
var testUsers = new Faker<User>()
    .CustomInstantiator(f => new User(userIds++, f.Random.Replace("###-##-####")))

The above code, could produce multiple Users with the same ID. I think we could do a better job here since we're expected to run in test runners.

Two main areas we need to be careful are:

  1. Careful accessing new randomness from Randomizer.Seed since Random isn't inherently thread-safe. This should protect against strange issues when using a DataSet by multiple threads. DataSet could possibly produce the same value multiple times when accessed by two or more threads.
  2. Faker<T>.Populate needs a lock to prevent multiple RuleFors from executing at the same time. Lambda closure outside-scope of Faker can be affected by multiple threads.

Possibly using a global lock, an internal lazy-static (Randomizer.Locker), to lock around Seed and Faker<T>.Populate should serialize threads and prevent from clobbering each other.

Random properties always changing values when Faker<T>.Generate(int) returned IEnumerable is stored as such

Here's a code sample in the context of a unit test class :

[TestClass]
public class UnitTestClass
{
	IEnumerable<User> fakeUsers;

	private class User
	{
		public string Name { get; set; }

		public DateTime CreatedAt { get; set; }
	}

	[TestInitialize]
	public void Initialize()
	{
		var userFaker = new Faker<User>()
						.RuleFor(t => t.Name, f => f.Name.FirstName())
						.RuleFor(t => t.CreatedAt, f => f.Date.Recent());

		fakeUsers = userFaker.Generate(3);
}

When running a unit test from that test class while watching the fakeUsers object, I noticed that the randomly generated values for the Name and CreatedAt would constantly change inbetween each debugging step. This means that the faked objects cannot be used for assertions, as the expected values are unstable and will never match the asserted values.

However, if I store the faked User objects in a List and use LINQ.ToList() on the Generate method's returned IEnumerable, the issue no longer occurs and the random values can be properly used.

A few suggestions for additional fake types

Here are a few ideas for additional fakes that I have needed that could be built in:

  • System.Version
  • System.TimeSpan
  • System.DateTimeOffset - Not major as DateTimeOffset has a conversion operator to DateTime.
  • System.Guid - Not major as Guid.NewGuid is just as easy.
  • Any Exception

Feature: add new RuleFor method

Hello,

When using Faker usually the following is used:

.RuleFor(x => x.Flag, y => "EBook File")

But in this simple cases why not have a new method do be used as:

.RuleFor(x => x.Key, "EBook File")

No need for the lambda expression ... So maybe adding a new RuleFor method:

public Faker<T> RuleFor<TProperty>(Expression<Func<T, TProperty>> property, TProperty setter)

Thank You

Consider upgrading NewtonSoft.Json to 7.0.0.0

Getting bit by the following in my test project referencing Json.NET 7.0:

System.TypeInitializationException: The type initializer for 'Tests.Framework.MockData.Project' threw
an exception. ---> System.IO.FileLoadException: Could not load file or assembly 'Newtonsoft.Json,
Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies.
The located assembly's manifest definition does not match the assembly reference. (Exception from
HRESULT: 0x80131040)
at Bogus.DataSets.Name.FirstName()

Love Bogus so far, it's replacing AutoPoco as my go to tool to create mock poco's πŸ‘

ArgumentException when creating new Faker on derived class with property using the 'new' modifier

I stumbled upon this issue when doing refactoring of our class hierarchies. The problem occurred when we introduced a few new base classes that have derived subclasses that use the 'new' modifier on a property.

We are running this on .NET 4.6.2 and Bogus 12.0.1. I have managed to reproduce the issue with the unit test below.

    [TestClass]
    public class BogusTest
    {
        [TestMethod]
        public void TestMethod1()
        {
            //Works
            var baseA = new Faker<BaseA>();

            //Throws System.ArgumentException: 'An item with the same key has already been added.'
            var derivedA = new Faker<DerivedA>();
        }
    }

    class BaseA
    {
        public BaseB SomeProp { get; set; }
    }

    class DerivedA : BaseA
    {
        public new DerivedB SomeProp { get; set; }
    }

    class BaseB
    {
        public int Value { get; set; }
    }

    class DerivedB : BaseB
    {
        public new int Value { get; set; }
    }

Define Hashids options in Faker

Would it be possible to make available HashIds options

public Hashids(string salt = "", int minHashLength = 0, string alphabet = DEFAULT_ALPHABET, string seps = DEFAULT_SEPS)

As faker options:

Faker.Hashids.Settings = new HashidsSettings {       
    Alphabet = "abcd";
}

So in this case the alphabet "abcd" would be used along with the other default options already defined in Hashids.

Thank You,
Miguel

Feature: Auto Populate by Convention?

Just thought:

Possibly have a method that can auto-populate a domain/DTO object if certain property conventions are met.

IE: when auto populating an object, if properties such as SSN and Phone or Telephone are encountered, auto populate them without having to setup fluent rules for that property.

I think it would reduce the amount of setup required to get started.

Sentence with minimum and maximum random of words

I need to create a sentence with 2 to 4 random words. I read the following:

Sentence - Get a random sentence. Default minimum of 3 words but at most 10 words (range = 7). If you want a sustenance with 5 words always call Sentence(5, range: 0);

Maybe I am missing something but it seems range is not being used ... Is it?

How can I define a minimum and maximum number of random words to be created in a sentence?

Provide implicit operator for <T>

Put an implicit operator for type on Faker so that I can do this:

public Faker<Thing> NormalThing = new Faker<Thing>
  .RuleFor(t => t.Name, f => f.Name.FirstName);

public Faker<Thing> HackerThing = DefaultThing
  .RuleFor(t => t.Handle, f => f.Hacker.Verb);

Thing normalThing = HackerThing;

Without the implicit operator, I either have to Generate in the consumer all the time, or copy various rules around the codebase. All the implicit operator would do is call Generate() - ShouldWork (tm).

If I get some time over the next week or so I'll try and code this up and send over a PR. Check this articule from Kenneth Truyers for more of an insight.

Profile 259 Compatibility?

Is there any version of Bogus that is compatible with PCL Profile 259 in Xamarin? I tried all the way up to 7.1.2, which is the one just before .NET Core support was official. I always get:

Could not install package 'Bogus 7.1.3'. You are trying to install this package into a project that targets '.NETPortable,Version=v4.5,Profile=Profile259'

when I try to add the the Nuget package.

Even though the Dependency is .NET 4.0 and 259 is Version=4.5 shouldn't I be able to add it? I thought dependencies were always >= <X.X>

Thanks.

Inabiltiy to use int.MaxValue in Randomizer.Number

The API documentation says that Randomizer.Number accepts inclusive range of (min, max) but it won't work with int.MaxValue for obvious reason. So, in my opinion the method documentation should mention it and a proper exception should be thrown because right now the exception is a bit misleading.

Would you consider adding a SortCode for banking data?

Although you've very well defined a BIC and an IBAN, I was wondering how easy it would be to get an option to add SortCode (6-digits) which are specific to the UK.
If not, is there an easy way to achieve this though the existing, built-in APIs?
Thanks for the great effort and tool btw

UniqueIndex not Unique in Parent -> Child relations.

If I understand the code and documentation correctly, UniqueIndex should be globaly unique. This is not the case when generating child objects.

Expected result UniqueIndex:
[{0, 1}, {2, 3}, {4, 5}]

Actual result UniqueIndex:
[{0, 0}, {2, 2}, {4, 4}]

var childFaker = new Faker<Child>()
   .RuleFor(u => u.Id, f => f.UniqueIndex);

var parentFaker = new Faker<Parent>()
   .RuleFor(u => u.Id, f => f.UniqueIndex)
   .RuleFor(u => u.Child, f => childFaker.Generate());

parentFaker.Generate(3).Select(o => new { o.Id, CId = o.Child.Id }).Dump(); //Dump: LinqPad only

However if I generate those individual like:

var childFaker = new Faker<Child>()
   .RuleFor(u => u.Id, f => f.UniqueIndex);

var parentFaker = new Faker<Parent>()
   .RuleFor(u => u.Id, f => f.UniqueIndex);

parentFaker.Generate(3).Dump();
childFaker.Generate(3).Dump();

The result will be like expected:
[0, 1, 2]
[3, 4, 5]

public class Parent
{
   public int Id { get; set; }
   public Child Child { get; set; }
}

public class Child
{
   public int Id { get; set; }
}

Edit: This might be related to #48
However the issue itself should different.
Testet in Bogus from NuGet v10.0.1

Intellisense doesn't work correctly with Faker

Not sure if this a bug with Visual Studio or just something odd about how the library was setup. I have actually worked with Fluent Validation before and wrote something similar to it but have never seen this issue. It uses the same mechanics of multiple expressions.

If I start typing this...
.RuleFor(o => o.
It won't provide any intellisense for the member properties

Yet, if I type a comma after the 'o.' it will start showing member properties. The comma has to be there for it to work.
So... .RuleFor(o => o.,

After typing the comma, I can go back and hit the dot again to start seeing intellisense. My intellisense works fine with everything else. I have tried exiting Visual Studio, etc. It seems to not like something specific about this library.

Override rules (or clone Faker)

I'd like to use a base Faker that I can then add additional rules to. A rudimentary example:

            var baseEntries = new Faker<BlogEntry>()
                .RuleFor(b => b.Title, f => f.Lorem.Sentence())
                .RuleFor(b => b.Summary, f => f.Lorem.Paragraph());

var publishedEntries = baseEntries.RuleFor(b => b.IsPublished, f => true);
var unpublishedEntries = baseEntries.RuleFor(b => b.IsPublished, f => false);

This currently throws an exception with message An item with the same key has already been added. because RuleFor is just inserting in to a dictionary, rather than adding or updating.

Is there a better way to do this? If not, could RuleFor be set up to do: this.Actions[propName] = invoker; instead of .Add(propName, invoker); in Faker[T].cs

PickRandom to accept a N parameter an return more than one item

Hello,

I think it would be really useful that PickRandom could return more than one item.

.RuleFor(x => x.Tags, y => tags.OrderBy(z => Guid.NewGuid()).Take(4).ToList())

I think instead the following could be done:

.RuleFor(x => x.Tags, y => y.PickRandom(tags, 4))

Internally, the following could be used:

collection.OrderBy(x => Guid.NewGuid()).Take(n)

or any other option ...

Thanks,
Miguel

UniqueIndex seems to generate repeating values

Hello,

I am getting a strange behavior with UniqueIndex. I have the following:

        Faker<Client> clients = new Faker<Client>()
          .RuleFor(x => x.Description, y => y.Lorem.Paragraphs(1))

        users.AddRange(
          new Faker<User>()
            .RuleFor(x => x.Name, y => new String[] { "John", "Mary", "Mike", "Tom" }[y.UniqueIndex % 4])
            .RuleFor(x => x.Email, (y, x) => { return $"{x.Name}@xyz.com".Replace(" ", "").ToLower(); })
            .RuleFor(x => x.Client, y => y.Random.Bool() ? clients.Generate(1).First() : null)
            .RuleFor(x => x.UserName, (y, x) => x.Email)
            .Generate(4).ToList());

I am getting four users with repeating names like: John, Mary, John, Mary ...

If I remove the line to generate the Client, e.g:

            .RuleFor(x => x.Client, y => y.Random.Bool() ? clients.Generate(1).First() : null)

Then it seems I get the four different names ... Any idea why?

Thank You

Feature: add distinct as an option

Hello,

Sometimes when inserting Usernames, Emails and other properties to a database the values must be unique. It would be nice to have a Distinct option in Bogus.

Thank You,
Miguel

Possible deadlock during populate internal

We use bogus in our unit/integration tests to generate fake data and sometimes we see the runner never completing and usually the pending threads look very similar to this:

image

The lock here:

lock( Randomizer.Locker.Value )

which directs to:

https://github.com/bchavez/Bogus/blob/master/Source/Bogus/Randomizer.cs#L22

feels like the culprit but have not spend enough time on it but it looks like that object does not need to be lazy?

Add a few extra Random Helpers

I suggest adding the following to Bogus:

  1. Generate a random Double between a Minimum and Maximum number:

    .RuleFor(x => x.Double, y => y.Random.Double(1, 4))

  2. Generate other random types as Single, Decimal, ...:

    .RuleFor(x => x.Decimal, y => y.Random.Decimal(1, 4))

What do you think?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.