Coder Social home page Coder Social logo

bchavez / bogus Goto Github PK

View Code? Open in Web Editor NEW
8.3K 120.0 471.0 6.06 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.11% PowerShell 0.24% Shell 0.16%
fake data generator dotnet csharp faker c-sharp bogus poco data-access-layer

bogus's People

Contributors

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 stanleygoldman 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

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 ???

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.

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

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.

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

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

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.

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

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;
    }

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 πŸ‘

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.

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?

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.

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 

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

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?

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?

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?

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

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.

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

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

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.

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 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

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

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?

.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.

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

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();
    }
}

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

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

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; }
    }

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.

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: 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

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.

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.

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?

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)

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.

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.