-
-
Notifications
You must be signed in to change notification settings - Fork 496
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feature: Global SkipRule
or Generic BeforeRule
preprocessor
#178
Comments
Hi @anorborg, Thank you for the complements! I'm really glad you like Bogus! It always makes me happy to hear from people using Bogus. 😎 To answer your question: using Bogus.Extensions;
void Main()
{
var fakeTests = new Faker<Test>()
.RuleFor( x => x.Value1, f => f.Random.Int(1, 5).OrNull(f) )
.RuleFor( x => x.Value2, f => f.Internet.Ip().OrNull(f) );
fakeTests.Generate(10).Dump();
}
public class Test
{
public int? Value1 {get; set;}
public string Value2 {get;set;}
} Currently, void Main()
{
var fakeTests = new Faker<Test>()
.RuleFor( x => x.Value1, f => f.Random.Int(1, 5).OrNull(f, 0.9f) )
.RuleFor( x => x.Value2, f => f.Internet.Ip().OrNull(f, 0.1f) );
fakeTests.Generate(10).Dump();
}
public static class MyBogusExtensions
{
public static object OrNull(this object value, Faker f, float nullWeight)
{
return f.Random.Float() < nullWeight ? null : value;
}
} The code above is quite clear, elegant, terse, and very readable IMHO. Perhaps, it might be a good idea to make this change official and allow the user to optionally specify the weight of nullability. 😺 Hope that helps! Thanks, //cc related #124 |
…hod for weighted generation of null values.
… method for weighted generation of null values.
Thanks! A small suggestion: use public static object OrDefault(this object value, Faker f, double defaultValueWeight = 0.5f)
{
if (defaultValueWeight > 1 || defaultValueWeight < 0) throw new ArgumentOutOfRangeException(nameof(defaultValueWeight), $".{nameof(OrDefault)}() {nameof(defaultValueWeight)} of '{defaultValueWeight}' must be between 1.0f and 0.0f. ");
return f.Random.Float() > defaultValueWeight ? value : default;
}
} Although you can define zero in your range in most, if not all cases, since you've added the weight, its a nice option to only select that value with the same probability as null. |
Hi @anorborg, That's a great idea! Thank you for the suggestion! I've released Bogus Hope that helps! Thanks, |
This is really an amazing tool, but would appreciate some sugar-syntax in my use-case to be able to vary in some
null
/unset values.What I do today
Suggested Feature Syntax
I'm not sure if there is a better/current way to accomplish something similar, but generating a dataset with the occasional null value is pretty useful for my in testing scenarios. Again, great tool!
The text was updated successfully, but these errors were encountered: