bchavez / bogus Goto Github PK
View Code? Open in Web Editor NEW:card_index: A simple fake data generator for C#, F#, and VB.NET. Based on and ported from the famed faker.js.
License: Other
:card_index: A simple fake data generator for C#, F#, and VB.NET. Based on and ported from the famed faker.js.
License: Other
PickRandom is great but when i want to pick a random subset of items it gets quickly complex.
I have to PickRandom multiple times and then do a distinct to be sure to not have doubles.
It would be great if a function for this existed.
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 ???
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.
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
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 User
s 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:
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.Faker<T>.Populate
needs a lock to prevent multiple RuleFor
s 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.
Do you have any intentions to support .NET Core (dotnet) DNX?
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
Hello,
Lovely lib!
I can't seem to use strict mode on an object which have read only properties. Bogus thinks that this object is not initialized.
Could this be a bug?
When I try to use bogus with linqpad ORM it throws this exception:
ArgumentException: Expression was not of the form 'x => x.property'.
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
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.
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
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;
}
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 π
To avoid having to register a public key on Github (some people don't want to), it should be changed to the default https:// version.
i.e. https://github.com/Marak/faker.js.git
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.
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?
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.
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.md "Images" section is inaccurate:
Images
but it's actually Image
ImageUrl
which is actually a protected methodHi 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:
However, some unittests are failing:
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?
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?
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:
The lock here:
Bogus/Source/Bogus/Faker[T].cs
Line 228 in 198bf73
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?
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
Hi,
Is it intentional that Faker class is missing Commerce
dataset that documented in readme?
Thanks.
CC: @eugene-senexx
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.
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
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
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.
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
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
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
I suggest adding the following to Bogus:
Generate a random Double between a Minimum and Maximum number:
.RuleFor(x => x.Double, y => y.Random.Double(1, 4))
Generate other random types as Single, Decimal, ...:
.RuleFor(x => x.Decimal, y => y.Random.Decimal(1, 4))
What do you think?
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.
For example on quite a wide class I only really want to define a rule for a couple of properties and and the rest can be random strings.
So something like
faker.DefaultRuleFor<string>(f => "a string")
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
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();
}
}
Here are a few ideas for additional fakes that I have needed that could be built in:
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
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; }
}
Lays the foundation for ultimately getting #8 done.
π π "Let the good times roll..."
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.
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:
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?
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
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.
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.
The Method Int()
of the Randomizer
class returns only the values int.MinValue
or int.MinValue+1
when called without parameters,
The default parameters suggest, that it should return any integer between int.MinValue
and int.MaxValue
.
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?
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)
f => f.Lorem.AsString(100)
would return "Lorem ipsum..." as string with exactly 100 characters in length.f => f.Random.Letter
would return any letter in alphabet randomly.f => f.Random.Enum<MyEnum>(exceptDefault: true)Β
Random.Replace()
could have placeholder for "digit-or-letter"Random.Replace()
, but better to have specific method for it.There are some ideas and needs - can they be added to Bogus, despite they are missing in faker.js?
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)
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 declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.