From f93dc167f3554dc0f641f4bf34f32721700b47d2 Mon Sep 17 00:00:00 2001 From: Brian Chavez Date: Sun, 24 Dec 2023 09:14:29 -0700 Subject: [PATCH] Tests: Use file-scoped namespaces. (#520) --- Source/Bogus.Tests/BsonTests.cs | 216 ++-- Source/Bogus.Tests/CloneTests.cs | 85 +- .../Bogus.Tests/DataSetTests/AddressTest.cs | 309 +++--- Source/Bogus.Tests/DataSetTests/CardTests.cs | 23 +- .../Bogus.Tests/DataSetTests/CommerceTest.cs | 123 ++- .../Bogus.Tests/DataSetTests/CompanyTest.cs | 95 +- .../Bogus.Tests/DataSetTests/DatabaseTests.cs | 53 +- Source/Bogus.Tests/DataSetTests/DateTest.cs | 691 +++++++------ .../DataSetTests/DateTest.net60.cs | 255 +++-- .../Bogus.Tests/DataSetTests/FinanceTest.cs | 373 ++++--- .../Bogus.Tests/DataSetTests/HackerTests.cs | 41 +- Source/Bogus.Tests/DataSetTests/ImageTest.cs | 203 ++-- .../Bogus.Tests/DataSetTests/InternetTests.cs | 289 +++--- Source/Bogus.Tests/DataSetTests/LoremTests.cs | 307 +++--- Source/Bogus.Tests/DataSetTests/MusicTests.cs | 31 +- Source/Bogus.Tests/DataSetTests/NameTests.cs | 339 ++++--- .../DataSetTests/PhoneNumbersTest.cs | 49 +- Source/Bogus.Tests/DataSetTests/RantTests.cs | 49 +- Source/Bogus.Tests/DataSetTests/SystemTest.cs | 289 +++--- .../Bogus.Tests/DataSetTests/VehicleTest.cs | 75 +- .../DistributionTests/GaussianTests.cs | 351 ++++--- .../ExtensionTests/ExtensionTest.cs | 549 ++++++----- .../ExtensionTests/NorwegianExtensionTest.cs | 159 ++- ...tionPlateExtensionsForGreatBritainTests.cs | 187 ++-- .../ExtensionTests/SwedishExtensionTest.cs | 93 +- Source/Bogus.Tests/ExtensionsForTesting.cs | 27 +- Source/Bogus.Tests/FluentTests.cs | 711 +++++++------- Source/Bogus.Tests/GitHubIssues/Issue10.cs | 109 +- Source/Bogus.Tests/GitHubIssues/Issue100.cs | 321 +++--- Source/Bogus.Tests/GitHubIssues/Issue102.cs | 45 +- Source/Bogus.Tests/GitHubIssues/Issue104.cs | 183 ++-- Source/Bogus.Tests/GitHubIssues/Issue114.cs | 29 +- Source/Bogus.Tests/GitHubIssues/Issue115.cs | 93 +- Source/Bogus.Tests/GitHubIssues/Issue121.cs | 115 ++- Source/Bogus.Tests/GitHubIssues/Issue124.cs | 355 ++++--- Source/Bogus.Tests/GitHubIssues/Issue126.cs | 109 +- Source/Bogus.Tests/GitHubIssues/Issue13.cs | 157 ++- Source/Bogus.Tests/GitHubIssues/Issue132.cs | 315 +++--- Source/Bogus.Tests/GitHubIssues/Issue134.cs | 69 +- Source/Bogus.Tests/GitHubIssues/Issue143.cs | 87 +- Source/Bogus.Tests/GitHubIssues/Issue152.cs | 19 +- Source/Bogus.Tests/GitHubIssues/Issue168.cs | 15 +- Source/Bogus.Tests/GitHubIssues/Issue169.cs | 15 +- Source/Bogus.Tests/GitHubIssues/Issue178.cs | 83 +- Source/Bogus.Tests/GitHubIssues/Issue179.cs | 97 +- Source/Bogus.Tests/GitHubIssues/Issue192.cs | 31 +- Source/Bogus.Tests/GitHubIssues/Issue193.cs | 213 ++-- Source/Bogus.Tests/GitHubIssues/Issue218.cs | 65 +- Source/Bogus.Tests/GitHubIssues/Issue225.cs | 51 +- Source/Bogus.Tests/GitHubIssues/Issue23.cs | 27 +- Source/Bogus.Tests/GitHubIssues/Issue232.cs | 53 +- Source/Bogus.Tests/GitHubIssues/Issue249.cs | 49 +- Source/Bogus.Tests/GitHubIssues/Issue253.cs | 131 ++- Source/Bogus.Tests/GitHubIssues/Issue255.cs | 241 +++-- Source/Bogus.Tests/GitHubIssues/Issue260.cs | 55 +- Source/Bogus.Tests/GitHubIssues/Issue271.cs | 17 +- Source/Bogus.Tests/GitHubIssues/Issue279.cs | 434 ++++---- Source/Bogus.Tests/GitHubIssues/Issue280.cs | 139 ++- Source/Bogus.Tests/GitHubIssues/Issue309.cs | 109 +- Source/Bogus.Tests/GitHubIssues/Issue313.cs | 32 +- Source/Bogus.Tests/GitHubIssues/Issue318.cs | 31 +- Source/Bogus.Tests/GitHubIssues/Issue319.cs | 49 +- Source/Bogus.Tests/GitHubIssues/Issue321.cs | 199 ++-- Source/Bogus.Tests/GitHubIssues/Issue328.cs | 21 +- Source/Bogus.Tests/GitHubIssues/Issue342.cs | 15 +- Source/Bogus.Tests/GitHubIssues/Issue355.cs | 15 +- Source/Bogus.Tests/GitHubIssues/Issue389.cs | 83 +- Source/Bogus.Tests/GitHubIssues/Issue411.cs | 61 +- Source/Bogus.Tests/GitHubIssues/Issue45.cs | 49 +- Source/Bogus.Tests/GitHubIssues/Issue48.cs | 81 +- Source/Bogus.Tests/GitHubIssues/Issue49.cs | 29 +- Source/Bogus.Tests/GitHubIssues/Issue55.cs | 144 ++- Source/Bogus.Tests/GitHubIssues/Issue61.cs | 41 +- Source/Bogus.Tests/GitHubIssues/Issue70.cs | 103 +- Source/Bogus.Tests/GitHubIssues/Issue86.cs | 45 +- Source/Bogus.Tests/GitHubIssues/Issue93.cs | 47 +- Source/Bogus.Tests/GitHubIssues/Issue99.cs | 17 +- .../GitHubIssues/PullRequest113.cs | 15 +- .../GitHubIssues/PullRequest149.cs | 15 +- .../GitHubIssues/PullRequest180.cs | 39 +- .../GitHubIssues/PullRequest194.cs | 55 +- .../GitHubIssues/PullRequest197.cs | 27 +- .../GitHubIssues/PullRequest258.cs | 39 +- .../GitHubIssues/PullRequest259.cs | 69 +- .../GitHubIssues/PullRequest261.cs | 43 +- .../GitHubIssues/PullRequest513.cs | 15 +- Source/Bogus.Tests/HandleBarTests.cs | 31 +- .../HandlebarsTests/ArgumentsTest.cs | 265 +++-- Source/Bogus.Tests/LocaleTests/PtLocale.cs | 81 +- Source/Bogus.Tests/LocaleTests/TrLocale.cs | 27 +- Source/Bogus.Tests/Models/Order.cs | 14 +- Source/Bogus.Tests/PersonTest.cs | 459 +++++---- Source/Bogus.Tests/README_Generator.cs | 521 +++++----- Source/Bogus.Tests/RandomizerTest.cs | 927 +++++++++--------- Source/Bogus.Tests/Rant_Generator.cs | 127 ++- Source/Bogus.Tests/RuleSetTests.cs | 323 +++--- Source/Bogus.Tests/SeededTest.cs | 45 +- .../Question60136934.cs | 107 +- .../Question66444118.cs | 81 +- Source/Bogus.Tests/StrictModeTests.cs | 213 ++-- Source/Bogus.Tests/TransliterateTests.cs | 103 +- Source/Bogus.Tests/UniquenessTests.cs | 243 +++-- Source/Bogus.Tests/ValidationDeltaTests.cs | 113 ++- 103 files changed, 7377 insertions(+), 7485 deletions(-) diff --git a/Source/Bogus.Tests/BsonTests.cs b/Source/Bogus.Tests/BsonTests.cs index 2f73f79f..3eb2cb60 100644 --- a/Source/Bogus.Tests/BsonTests.cs +++ b/Source/Bogus.Tests/BsonTests.cs @@ -6,133 +6,131 @@ using Xunit; using Xunit.Abstractions; -namespace Bogus.Tests +namespace Bogus.Tests; + +public class ExtraStuff : DataSet { - public class ExtraStuff : DataSet + public string JunkFood() { - public string JunkFood() - { - return this.GetRandomArrayItem("junkfood"); - } - - public string Drink() - { - return this.GetRandomArrayItem("Drink"); - } + return this.GetRandomArrayItem("junkfood"); } - public class BsonTests : SeededTest, IDisposable + public string Drink() { - private readonly ITestOutputHelper console; + return this.GetRandomArrayItem("Drink"); + } +} - public BsonTests(ITestOutputHelper console) - { - this.console = console; - } +public class BsonTests : SeededTest, IDisposable +{ + private readonly ITestOutputHelper console; - public void Dispose() - { - Database.ResetLocale("en"); - Database.ResetLocale("it"); - } + public BsonTests(ITestOutputHelper console) + { + this.console = console; + } - [Fact] - public void can_add_new_key_to_database() - { - PatchEnLocaleWithExtraStuff(); + public void Dispose() + { + Database.ResetLocale("en"); + Database.ResetLocale("it"); + } - var extra = new ExtraStuff(); - extra.JunkFood().Should().Be("Pizza"); - extra.Drink().Should().Be("Pepsi"); - } + [Fact] + public void can_add_new_key_to_database() + { + PatchEnLocaleWithExtraStuff(); - [Fact] - public void should_be_able_to_reset_a_locale() - { - PatchEnLocaleWithExtraStuff(); + var extra = new ExtraStuff(); + extra.JunkFood().Should().Be("Pizza"); + extra.Drink().Should().Be("Pepsi"); + } - var extra = new ExtraStuff(); + [Fact] + public void should_be_able_to_reset_a_locale() + { + PatchEnLocaleWithExtraStuff(); - extra.JunkFood().Should().Be("Pizza"); + var extra = new ExtraStuff(); - Database.ResetLocale("en"); + extra.JunkFood().Should().Be("Pizza"); - Action error = () => extra.JunkFood().Should().Be("Pizza"); + Database.ResetLocale("en"); - error.Should().Throw(); - } + Action error = () => extra.JunkFood().Should().Be("Pizza"); + error.Should().Throw(); + } - [Fact] - public void can_patch_an_existing_category() - { - //names use only these first names - var names = new[] {"Brian", "Chris", "Anthony", "Charlie", "Megan"}; - - //make a BArray out of the names we wish to use - var firstNames = names.Aggregate(new BArray(), (ba, name) => + + [Fact] + public void can_patch_an_existing_category() + { + //names use only these first names + var names = new[] {"Brian", "Chris", "Anthony", "Charlie", "Megan"}; + + //make a BArray out of the names we wish to use + var firstNames = names.Aggregate(new BArray(), (ba, name) => + { + ba.Add(name); + return ba; + }); + + //Get the locale we wish to mutate. + var itLocale = Database.GetLocale("it"); + + //get the locale's name category + var namesObject = itLocale["name"] as BObject; + + //In the name category, over-write the first_name category + namesObject["first_name"] = firstNames; + + //now test everything. get the 'it' locale. + var nameDataSet = new Name("it"); + + //get 10 names, + var namesFromDataSet = Make(10, () => nameDataSet.FirstName()) + .Distinct(); + + //and we should only have the one's we have patched. + namesFromDataSet.Should().BeEquivalentTo(names); + } + + + private void PatchEnLocaleWithExtraStuff() + { + var patch = CreateExtraData(); + var enLocale = Database.GetLocale("en"); + + // DATA SET NAMES ARE LOWERCASE. + enLocale.Add("extrastuff", patch); + } + + private BObject CreateExtraData() + { + //patching a data set looks like: + // { + // "category1": [item1, item2,...] + // "category2": [item1, item2,...] + // } + return new BObject + { { - ba.Add(name); - return ba; - }); - - //Get the locale we wish to mutate. - var itLocale = Database.GetLocale("it"); - - //get the locale's name category - var namesObject = itLocale["name"] as BObject; - - //In the name category, over-write the first_name category - namesObject["first_name"] = firstNames; - - //now test everything. get the 'it' locale. - var nameDataSet = new Name("it"); - - //get 10 names, - var namesFromDataSet = Make(10, () => nameDataSet.FirstName()) - .Distinct(); - - //and we should only have the one's we have patched. - namesFromDataSet.Should().BeEquivalentTo(names); - } - - - private void PatchEnLocaleWithExtraStuff() - { - var patch = CreateExtraData(); - var enLocale = Database.GetLocale("en"); - - // DATA SET NAMES ARE LOWERCASE. - enLocale.Add("extrastuff", patch); - } - - private BObject CreateExtraData() - { - //patching a data set looks like: - // { - // "category1": [item1, item2,...] - // "category2": [item1, item2,...] - // } - return new BObject + "junkfood", new BArray + { + "Cookies", + "Pizza", + "Chips" + } + }, { - { - "junkfood", new BArray - { - "Cookies", - "Pizza", - "Chips" - } - }, - { - "Drink", new BArray - { - "Pepsi", - "Coca-Cola", - "Sprite" - } - } - }; - } + "Drink", new BArray + { + "Pepsi", + "Coca-Cola", + "Sprite" + } + } + }; } - } diff --git a/Source/Bogus.Tests/CloneTests.cs b/Source/Bogus.Tests/CloneTests.cs index dafa360c..89e44684 100644 --- a/Source/Bogus.Tests/CloneTests.cs +++ b/Source/Bogus.Tests/CloneTests.cs @@ -1,50 +1,49 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests +namespace Bogus.Tests; + +public class CloneTests : SeededTest { - public class CloneTests : SeededTest + [Fact] + public void can_create_a_simple_clone() + { + var orderFaker = new Faker() + .UseSeed(88) + .RuleFor(o => o.OrderId, f => f.IndexVariable++) + .RuleFor(o => o.Quantity, f => f.Random.Number(1, 3)) + .RuleFor(o => o.Item, f => f.Commerce.Product()); + + var clone = orderFaker.Clone(); + + var clonedOrder = clone.Generate(); + + var rootOrder = orderFaker.Generate(); + + clonedOrder.Should().BeEquivalentTo(rootOrder); + } + + [Fact] + public void clone_has_different_rules() { - [Fact] - public void can_create_a_simple_clone() - { - var orderFaker = new Faker() - .UseSeed(88) - .RuleFor(o => o.OrderId, f => f.IndexVariable++) - .RuleFor(o => o.Quantity, f => f.Random.Number(1, 3)) - .RuleFor(o => o.Item, f => f.Commerce.Product()); - - var clone = orderFaker.Clone(); - - var clonedOrder = clone.Generate(); - - var rootOrder = orderFaker.Generate(); - - clonedOrder.Should().BeEquivalentTo(rootOrder); - } - - [Fact] - public void clone_has_different_rules() - { - var rootFaker = new Faker() - .UseSeed(88) - .RuleFor(o => o.OrderId, f => f.IndexVariable++) - .RuleFor(o => o.Quantity, f => f.Random.Number(1, 3)) - .RuleFor(o => o.Item, f => f.Commerce.Product()); - - var cloneFaker = rootFaker.Clone() - .RuleFor(o => o.Quantity, f => f.Random.Number(4, 6)); - - var rootOrder = rootFaker.Generate(); - var clonedOrder = cloneFaker.Generate(); - - rootOrder.Quantity.Should() - .BeGreaterOrEqualTo(1).And - .BeLessOrEqualTo(3); - - clonedOrder.Quantity.Should() - .BeGreaterOrEqualTo(4).And - .BeLessOrEqualTo(6); - } + var rootFaker = new Faker() + .UseSeed(88) + .RuleFor(o => o.OrderId, f => f.IndexVariable++) + .RuleFor(o => o.Quantity, f => f.Random.Number(1, 3)) + .RuleFor(o => o.Item, f => f.Commerce.Product()); + + var cloneFaker = rootFaker.Clone() + .RuleFor(o => o.Quantity, f => f.Random.Number(4, 6)); + + var rootOrder = rootFaker.Generate(); + var clonedOrder = cloneFaker.Generate(); + + rootOrder.Quantity.Should() + .BeGreaterOrEqualTo(1).And + .BeLessOrEqualTo(3); + + clonedOrder.Quantity.Should() + .BeGreaterOrEqualTo(4).And + .BeLessOrEqualTo(6); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/DataSetTests/AddressTest.cs b/Source/Bogus.Tests/DataSetTests/AddressTest.cs index 3b4888cf..9dd26950 100644 --- a/Source/Bogus.Tests/DataSetTests/AddressTest.cs +++ b/Source/Bogus.Tests/DataSetTests/AddressTest.cs @@ -3,161 +3,160 @@ using Xunit; using Xunit.Abstractions; -namespace Bogus.Tests.DataSetTests +namespace Bogus.Tests.DataSetTests; + +public class AddressTest : SeededTest { - public class AddressTest : SeededTest - { - private readonly ITestOutputHelper console; - - public AddressTest(ITestOutputHelper console) - { - this.console = console; - address = new Address(); - } - - private readonly Address address; - - [Fact] - public void can_get_a_city_name() - { - address.City().Should().Be("Bernhardfort"); - } - - [Fact] - public void can_get_a_country() - { - address.Country().Should().Be("Mozambique"); - } - - [Fact] - public void can_get_a_county() - { - address.County().Should().Be("Borders"); - } - - [Fact] - public void can_get_a_full_address() - { - address.FullAddress().Should().Be("60643 Oberbrunner Bypass, Danielchester, Monaco"); - } - - [Fact] - public void can_get_a_full_street_address() - { - address.StreetAddress(true).Should().Be("60643 Oberbrunner Bypass Suite 175"); - } - - [Fact] - public void can_get_a_latitude() - { - address.Latitude().Should().Be(18.634); - } - - [Fact] - public void can_get_a_longitude() - { - address.Latitude().Should().Be(18.634); - } - - [Fact] - public void can_get_a_random_country_code() - { - address.CountryCode().Should().Be("MR"); - } - - [Fact] - public void can_get_a_random_country_code_alpha3() - { - address.CountryCode(Iso3166Format.Alpha3).Should().Be("CMR"); - } - - [Fact] - public void can_get_a_state() - { - address.State().Should().Be("New Mexico"); - } - - [Fact] - public void can_get_a_state_abbreviation() - { - address.StateAbbr().Should().Be("NM"); - } - - [Fact] - public void can_get_a_street_address() - { - address.StreetAddress().Should().Be("60643 Oberbrunner Bypass"); - } - - [Fact] - public void can_get_a_street_suffix() - { - address.StreetSuffix().Should().Be("Pines"); - } - - [Fact] - public void can_get_a_zipcode() - { - address.ZipCode().Should().Be("18606-0643"); - } - - [Fact] - public void can_get_canadian_zip_code() - { - var a = new Address("en_CA"); - a.ZipCode().Should().Be("N1V 6A6"); - } - - [Fact] - public void can_get_a_city_prefix() - { - address.CityPrefix().Should().Be("New"); - } - - [Fact] - public void can_get_a_city_suffix() - { - address.CitySuffix().Should().Be("stad"); - } - - [Fact] - public void can_get_a_street_name() - { - address.StreetName().Should().Be("Brekke Stravenue"); - } - - [Fact] - public void can_get_a_building_number() - { - address.BuildingNumber().Should().Be("1860"); - } - - [Fact] - public void locales_with_no_state_should_return_null() - { - var a = new Address("az"); - a.State().Should().BeNullOrEmpty(); - } - - [Fact] - public void can_generate_a_direction() - { - address.Direction().Should().Be("Northeast"); - address.Direction(true).Should().Be("N"); - } - - [Fact] - public void can_generate_a_cardinal_direction() - { - address.CardinalDirection().Should().Be("South"); - address.CardinalDirection(true).Should().Be("N"); - } - - [Fact] - public void can_generate_an_ordinal_direction() - { - address.OrdinalDirection().Should().Be("Southeast"); - address.OrdinalDirection(true).Should().Be("NE"); - } + private readonly ITestOutputHelper console; + + public AddressTest(ITestOutputHelper console) + { + this.console = console; + address = new Address(); + } + + private readonly Address address; + + [Fact] + public void can_get_a_city_name() + { + address.City().Should().Be("Bernhardfort"); + } + + [Fact] + public void can_get_a_country() + { + address.Country().Should().Be("Mozambique"); + } + + [Fact] + public void can_get_a_county() + { + address.County().Should().Be("Borders"); + } + + [Fact] + public void can_get_a_full_address() + { + address.FullAddress().Should().Be("60643 Oberbrunner Bypass, Danielchester, Monaco"); + } + + [Fact] + public void can_get_a_full_street_address() + { + address.StreetAddress(true).Should().Be("60643 Oberbrunner Bypass Suite 175"); + } + + [Fact] + public void can_get_a_latitude() + { + address.Latitude().Should().Be(18.634); + } + + [Fact] + public void can_get_a_longitude() + { + address.Latitude().Should().Be(18.634); + } + + [Fact] + public void can_get_a_random_country_code() + { + address.CountryCode().Should().Be("MR"); + } + + [Fact] + public void can_get_a_random_country_code_alpha3() + { + address.CountryCode(Iso3166Format.Alpha3).Should().Be("CMR"); + } + + [Fact] + public void can_get_a_state() + { + address.State().Should().Be("New Mexico"); + } + + [Fact] + public void can_get_a_state_abbreviation() + { + address.StateAbbr().Should().Be("NM"); + } + + [Fact] + public void can_get_a_street_address() + { + address.StreetAddress().Should().Be("60643 Oberbrunner Bypass"); + } + + [Fact] + public void can_get_a_street_suffix() + { + address.StreetSuffix().Should().Be("Pines"); + } + + [Fact] + public void can_get_a_zipcode() + { + address.ZipCode().Should().Be("18606-0643"); + } + + [Fact] + public void can_get_canadian_zip_code() + { + var a = new Address("en_CA"); + a.ZipCode().Should().Be("N1V 6A6"); + } + + [Fact] + public void can_get_a_city_prefix() + { + address.CityPrefix().Should().Be("New"); + } + + [Fact] + public void can_get_a_city_suffix() + { + address.CitySuffix().Should().Be("stad"); + } + + [Fact] + public void can_get_a_street_name() + { + address.StreetName().Should().Be("Brekke Stravenue"); + } + + [Fact] + public void can_get_a_building_number() + { + address.BuildingNumber().Should().Be("1860"); + } + + [Fact] + public void locales_with_no_state_should_return_null() + { + var a = new Address("az"); + a.State().Should().BeNullOrEmpty(); + } + + [Fact] + public void can_generate_a_direction() + { + address.Direction().Should().Be("Northeast"); + address.Direction(true).Should().Be("N"); + } + + [Fact] + public void can_generate_a_cardinal_direction() + { + address.CardinalDirection().Should().Be("South"); + address.CardinalDirection(true).Should().Be("N"); + } + + [Fact] + public void can_generate_an_ordinal_direction() + { + address.OrdinalDirection().Should().Be("Southeast"); + address.OrdinalDirection(true).Should().Be("NE"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/DataSetTests/CardTests.cs b/Source/Bogus.Tests/DataSetTests/CardTests.cs index 8ec0910f..b948a836 100644 --- a/Source/Bogus.Tests/DataSetTests/CardTests.cs +++ b/Source/Bogus.Tests/DataSetTests/CardTests.cs @@ -1,21 +1,20 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.DataSetTests +namespace Bogus.Tests.DataSetTests; + +public class CardTests : SeededTest { - public class CardTests : SeededTest + [Fact] + public void should_be_able_to_get_a_contextually_bogus_person() { - [Fact] - public void should_be_able_to_get_a_contextually_bogus_person() - { - var card = new Person(); + var card = new Person(); - card.FirstName.Should().Be("Doris"); - card.LastName.Should().Be("Schultz"); - card.UserName.Should().Be("Doris.Schultz"); - card.Email.Should().Be("Doris69@yahoo.com"); + card.FirstName.Should().Be("Doris"); + card.LastName.Should().Be("Schultz"); + card.UserName.Should().Be("Doris.Schultz"); + card.Email.Should().Be("Doris69@yahoo.com"); - card.Dump(); - } + card.Dump(); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/DataSetTests/CommerceTest.cs b/Source/Bogus.Tests/DataSetTests/CommerceTest.cs index 00fc7adf..b821ea46 100644 --- a/Source/Bogus.Tests/DataSetTests/CommerceTest.cs +++ b/Source/Bogus.Tests/DataSetTests/CommerceTest.cs @@ -2,81 +2,80 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.DataSetTests +namespace Bogus.Tests.DataSetTests; + +public class CommerceTest : SeededTest { - public class CommerceTest : SeededTest + public CommerceTest() { - public CommerceTest() - { - commerce = new Commerce(); - } + commerce = new Commerce(); + } - private readonly Commerce commerce; + private readonly Commerce commerce; - [Fact] - public void can_get_a_color() - { - commerce.Color().Should().Be("plum"); - } + [Fact] + public void can_get_a_color() + { + commerce.Color().Should().Be("plum"); + } - [Fact] - public void can_get_a_product() - { - commerce.Product().Should().Be("Soap"); - } + [Fact] + public void can_get_a_product() + { + commerce.Product().Should().Be("Soap"); + } - [Fact] - public void can_get_a_product_adj() - { - commerce.ProductAdjective().Should().Be("Generic"); - } + [Fact] + public void can_get_a_product_adj() + { + commerce.ProductAdjective().Should().Be("Generic"); + } - [Fact] - public void can_get_a_product_material() - { - commerce.ProductMaterial().Should().Be("Rubber"); - } + [Fact] + public void can_get_a_product_material() + { + commerce.ProductMaterial().Should().Be("Rubber"); + } - [Fact] - public void can_get_a_product_name() - { - commerce.ProductName().Should().Be("Generic Wooden Bacon"); - } + [Fact] + public void can_get_a_product_name() + { + commerce.ProductName().Should().Be("Generic Wooden Bacon"); + } - [Fact] - public void can_get_a_product_description() - { - commerce.ProductDescription().Should().Be("Carbonite web goalkeeper gloves are ergonomically designed to give easy fit"); - } + [Fact] + public void can_get_a_product_description() + { + commerce.ProductDescription().Should().Be("Carbonite web goalkeeper gloves are ergonomically designed to give easy fit"); + } - [Fact] - public void can_get_categories() - { - commerce.Categories(3).Should().BeEquivalentTo(new[] {"Kids", "Music", "Jewelery"}, opt => opt.WithStrictOrdering()); - } + [Fact] + public void can_get_categories() + { + commerce.Categories(3).Should().BeEquivalentTo(new[] {"Kids", "Music", "Jewelery"}, opt => opt.WithStrictOrdering()); + } - [Fact] - public void can_get_list_of_departments() - { - commerce.Department(5).Should().Be("Music, Jewelery, Baby & Books"); - } + [Fact] + public void can_get_list_of_departments() + { + commerce.Department(5).Should().Be("Music, Jewelery, Baby & Books"); + } - [Fact] - public void can_get_price() - { - commerce.Price(symbol: "$").Dump(); - } + [Fact] + public void can_get_price() + { + commerce.Price(symbol: "$").Dump(); + } - [Fact] - public void can_get_ean8_barcode() - { - commerce.Ean8().Should().Be("61860605"); - } + [Fact] + public void can_get_ean8_barcode() + { + commerce.Ean8().Should().Be("61860605"); + } - [Fact] - public void can_get_an_ean13_barcode() - { - commerce.Ean13().Should().Be("6186060643914"); - } + [Fact] + public void can_get_an_ean13_barcode() + { + commerce.Ean13().Should().Be("6186060643914"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/DataSetTests/CompanyTest.cs b/Source/Bogus.Tests/DataSetTests/CompanyTest.cs index f7c8b19f..83103d08 100644 --- a/Source/Bogus.Tests/DataSetTests/CompanyTest.cs +++ b/Source/Bogus.Tests/DataSetTests/CompanyTest.cs @@ -4,65 +4,64 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.DataSetTests +namespace Bogus.Tests.DataSetTests; + +public class CompanyTest : SeededTest { - public class CompanyTest : SeededTest + public CompanyTest() { - public CompanyTest() - { - company = new Company(); - } + company = new Company(); + } - private readonly Company company; + private readonly Company company; - [Fact] - public void can_get_a_catch_phrase() - { - company.CatchPhrase().Should().Be("Phased background protocol"); - } + [Fact] + public void can_get_a_catch_phrase() + { + company.CatchPhrase().Should().Be("Phased background protocol"); + } - [Fact] - public void can_get_a_company_name_with_custom_format() - { - company.CompanyName(0).Should().Be("Mitchell Inc"); - } + [Fact] + public void can_get_a_company_name_with_custom_format() + { + company.CompanyName(0).Should().Be("Mitchell Inc"); + } - [Fact] - public void can_get_company_bs_phrase() - { - company.Bs().Should().Be("maximize leading-edge networks"); //lol - } + [Fact] + public void can_get_company_bs_phrase() + { + company.Bs().Should().Be("maximize leading-edge networks"); //lol + } - [Fact] - public void can_get_company_name() - { - company.CompanyName().Should().Be("Brekke - Schultz"); - } + [Fact] + public void can_get_company_name() + { + company.CompanyName().Should().Be("Brekke - Schultz"); + } - [Fact] - public void can_get_company_suffix_array() - { - var arr = company.Suffixes(); + [Fact] + public void can_get_company_suffix_array() + { + var arr = company.Suffixes(); - arr.Length.Should().NotBe(0); - } + arr.Length.Should().NotBe(0); + } - [Fact] - public void can_generate_cnpj_for_brazil() - { - company.Cnpj().Should().Be("61.860.606/0001-91"); - } + [Fact] + public void can_generate_cnpj_for_brazil() + { + company.Cnpj().Should().Be("61.860.606/0001-91"); + } - [Fact] - public void can_generate_cnpj_for_brazil_without_formatting() - { - company.Cnpj(includeFormatSymbols: false).Should().Be("61860606000191"); - } + [Fact] + public void can_generate_cnpj_for_brazil_without_formatting() + { + company.Cnpj(includeFormatSymbols: false).Should().Be("61860606000191"); + } - [Fact] - public void can_generate_an_EIN() - { - company.Ein().Should().Be("61-8606064"); - } + [Fact] + public void can_generate_an_EIN() + { + company.Ein().Should().Be("61-8606064"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/DataSetTests/DatabaseTests.cs b/Source/Bogus.Tests/DataSetTests/DatabaseTests.cs index 1ec36322..02e69be8 100644 --- a/Source/Bogus.Tests/DataSetTests/DatabaseTests.cs +++ b/Source/Bogus.Tests/DataSetTests/DatabaseTests.cs @@ -1,39 +1,38 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.DataSetTests +namespace Bogus.Tests.DataSetTests; + +public class DatabaseTests : SeededTest { - public class DatabaseTests : SeededTest + public DatabaseTests() { - public DatabaseTests() - { - database = new DataSets.Database(); - } + database = new DataSets.Database(); + } - private readonly DataSets.Database database; + private readonly DataSets.Database database; - [Fact] - public void can_generate_a_column_name() - { - database.Column().Should().Be("password"); - } + [Fact] + public void can_generate_a_column_name() + { + database.Column().Should().Be("password"); + } - [Fact] - public void can_generate_a_type() - { - database.Type().Should().Be("real"); - } + [Fact] + public void can_generate_a_type() + { + database.Type().Should().Be("real"); + } - [Fact] - public void can_generate_collation() - { - database.Collation().Should().Be("ascii_general_ci"); - } + [Fact] + public void can_generate_collation() + { + database.Collation().Should().Be("ascii_general_ci"); + } - [Fact] - public void can_generate_engine() - { - database.Engine().Should().Be("CSV"); - } + [Fact] + public void can_generate_engine() + { + database.Engine().Should().Be("CSV"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/DataSetTests/DateTest.cs b/Source/Bogus.Tests/DataSetTests/DateTest.cs index 076c69b7..ad967486 100644 --- a/Source/Bogus.Tests/DataSetTests/DateTest.cs +++ b/Source/Bogus.Tests/DataSetTests/DateTest.cs @@ -4,353 +4,352 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.DataSetTests +namespace Bogus.Tests.DataSetTests; + +public partial class DateTest : SeededTest { - public partial class DateTest : SeededTest + public DateTest() + { + date = new Date(); + } + + private readonly Date date; + + [Fact] + public void can_get_a_random_month() + { + date.Month().Should().NotBeNullOrEmpty(); + date.Month(true).Should().NotBeNullOrEmpty(); + } + + [Fact] + public void can_get_a_random_weekday() + { + date.Weekday().Should().NotBeNullOrEmpty(); + date.Weekday(true).Should().NotBeNullOrEmpty(); + } + + [Fact] + public void can_get_a_timespan() + { + date.Timespan().Should().BePositive() + .And + .BeGreaterThan(TimeSpan.Zero) + .And + .BeLessThan(TimeSpan.FromDays(7)); + } + + + [Fact] + public void can_get_date_in_future() + { + var starting = DateTime.Parse("6/7/2015 4:17:41 PM"); + date.Future(refDate: starting).Should() + .BeOnOrBefore(starting.AddYears(1)) + .And + .BeOnOrAfter(starting); + } + + [Fact] + public void can_get_dateOffset_in_future() + { + var starting = DateTimeOffset.Parse("6/7/2015 4:17:41 PM"); + date.FutureOffset(refDate: starting).Should() + .BeOnOrBefore(starting.AddYears(1)) + .And + .BeOnOrAfter(starting); + } + + [Fact] + public void can_get_date_in_future_with_options() + { + var starting = DateTime.Parse("6/15/2000 4:17:41 PM", CultureInfo.InvariantCulture); + date.Future(refDate: starting, yearsToGoForward: 5).Should() + .BeOnOrBefore(starting.AddYears(5)) + .And + .BeOnOrAfter(starting); + } + + [Fact] + public void can_get_dateOffset_in_future_with_options() + { + var starting = DateTimeOffset.Parse("6/15/2000 4:17:41 PM", CultureInfo.InvariantCulture); + date.FutureOffset(refDate: starting, yearsToGoForward: 5).Should() + .BeOnOrBefore(starting.AddYears(5)) + .And + .BeOnOrAfter(starting); + } + + [Fact] + public void can_get_date_in_past() + { + var starting = DateTime.Parse("6/7/2015 4:17:41 PM"); + date.Past(refDate: starting).Should() + .BeOnOrBefore(starting) + .And + .BeOnOrAfter(starting.AddYears(-1)); + } + + [Fact] + public void can_get_dateOffset_in_past() + { + var starting = DateTimeOffset.Parse("6/7/2015 4:17:41 PM"); + date.PastOffset(refDate: starting).Should() + .BeOnOrBefore(starting) + .And + .BeOnOrAfter(starting.AddYears(-1)); + } + + [Fact] + public void can_get_date_in_past_0_days_results_in_random_time() + { + date.Recent(0).Should() + .BeOnOrBefore(DateTime.Now) + .And + .BeOnOrAfter(DateTime.Now.Date); + } + + [Fact] + public void can_get_dateOffset_in_past_0_days_results_in_random_time() + { + date.RecentOffset(0).Should() + .BeOnOrBefore(DateTimeOffset.Now) + .And + .BeOnOrAfter(DateTimeOffset.Now.Date); + } + + [Fact] + public void can_get_date_in_past_with_custom_options() + { + var starting = DateTime.Parse("6/15/2000 4:17:41 PM", CultureInfo.InvariantCulture); + date.Past(refDate: starting, yearsToGoBack: 5).Should() + .BeOnOrBefore(starting) + .And + .BeOnOrAfter(starting.AddYears(-5)); + } + + [Fact] + public void can_get_dateOffset_in_past_with_custom_options() + { + var starting = DateTimeOffset.Parse("6/15/2000 4:17:41 PM", CultureInfo.InvariantCulture); + date.PastOffset(refDate: starting, yearsToGoBack: 5).Should() + .BeOnOrBefore(starting) + .And + .BeOnOrAfter(starting.AddYears(-5)); + } + + [Fact] + public void can_get_date_recently_within_the_year() + { + var start = DateTime.Now; + date.Recent() + .Should() + .BeOnOrBefore(start) + .And + .BeOnOrAfter(start.AddDays(-1)); + } + + [Fact] + public void can_get_dateOffset_recently_within_the_year() + { + var start = DateTimeOffset.Now; + date.RecentOffset() + .Should() + .BeOnOrBefore(start) + .And + .BeOnOrAfter(start.AddDays(-1)); + } + + [Fact] + public void can_get_random_time_between_two_dates() + { + var start = DateTime.Parse("6/15/2000 4:17:41 PM", CultureInfo.InvariantCulture); + var end = DateTime.Parse("8/15/2000 4:17:41 PM", CultureInfo.InvariantCulture); + + date.Between(start, end) + .Should() + .BeOnOrAfter(start) + .And + .BeOnOrBefore(end); + + //and reverse... + date.Between(end, start) + .Should() + .BeOnOrAfter(start) + .And + .BeOnOrBefore(end); + } + + [Fact] + public void can_get_random_time_between_two_dateOffsets() + { + var start = DateTimeOffset.Parse("6/15/2000 4:17:41 PM", CultureInfo.InvariantCulture); + var end = DateTimeOffset.Parse("8/15/2000 4:17:41 PM", CultureInfo.InvariantCulture); + + date.BetweenOffset(start, end) + .Should() + .BeOnOrAfter(start) + .And + .BeOnOrBefore(end); + + //and reverse... + date.BetweenOffset(end, start) + .Should() + .BeOnOrAfter(start) + .And + .BeOnOrBefore(end); + } + + [Fact] + public void get_a_date_that_will_happen_soon() + { + var now = DateTime.Now; + date.Soon(3).Should().BeAfter(now).And.BeBefore(now.AddDays(3)); + } + + [Fact] + public void get_a_dateOffsets_that_will_happen_soon() + { + var now = DateTimeOffset.Now; + date.SoonOffset(3).Should().BeAfter(now).And.BeBefore(now.AddDays(3)); + } + + [Fact] + public void soon_explicit_refdate_in_utc_should_return_utc_kind() + { + const int days = 3; + var dt = DateTime.Parse("7/5/2018 9:00 AM"); + var utc = DateTime.SpecifyKind(dt, DateTimeKind.Utc); + var utcEnd = utc.AddDays(days); + var result = date.Soon(days, utc); + + result.Kind.Should().Be(DateTimeKind.Utc); + + result.Should() + .BeOnOrAfter(utc) + .And + .BeOnOrBefore(utcEnd); + } + + [Fact] + public void soon_explicit_refdate_offset_should_return_explicit_offset() + { + const int days = 3; + var offset = TimeSpan.FromHours(-3); + var utc = DateTimeOffset.Parse("7/5/2018 9:00 AM").ToOffset(offset); + var utcEnd = utc.AddDays(days); + var result = date.SoonOffset(days, utc); + + result.Offset.Should().Be(offset); + + result.Should() + .BeOnOrAfter(utc) + .And + .BeOnOrBefore(utcEnd); + } + + [Fact] + public void recent_explicit_refdate_in_utc_should_return_utc_kind() + { + const int days = 3; + var dt = DateTime.Parse("7/5/2018 9:00 AM"); + var utcEnd = DateTime.SpecifyKind(dt, DateTimeKind.Utc); + var utcPast = utcEnd.AddDays(-days); + var result = date.Recent(days, utcEnd); + + result.Kind.Should().Be(DateTimeKind.Utc); + + result.Should() + .BeOnOrAfter(utcPast) + .And + .BeOnOrBefore(utcEnd); + } + + [Fact] + public void recent_explicit_refdate_offset_should_return_explicit_offset() + { + const int days = 3; + var offset = TimeSpan.FromHours(-3); + var utcEnd = DateTimeOffset.Parse("7/5/2018 9:00 AM").ToOffset(offset); + var utcPast = utcEnd.AddDays(-days); + var result = date.RecentOffset(days, utcEnd); + + result.Offset.Should().Be(offset); + + result.Should() + .BeOnOrAfter(utcPast) + .And + .BeOnOrBefore(utcEnd); + } + + [Fact] + public void between_explicit_refdate_in_utc_should_return_utc_kind() + { + const int days = 3; + var dt = DateTime.Parse("8/8/2017 10:00 AM"); + var utc = DateTime.SpecifyKind(dt, DateTimeKind.Utc); + var utcEnd = utc.AddDays(days); + var result = date.Between(utc, utcEnd); + + result.Kind.Should().Be(DateTimeKind.Utc); + + result.Should() + .BeOnOrAfter(utc) + .And + .BeOnOrBefore(utcEnd); + } + + [Fact] + public void between_explicit_start_offset_should_return_explicit_offset() + { + const int days = 3; + var offset = TimeSpan.FromHours(-3); + var utc = DateTimeOffset.Parse("8/8/2017 10:00 AM").ToOffset(offset); + var utcEnd = utc.AddDays(days); + var result = date.BetweenOffset(utc, utcEnd); + + result.Offset.Should().Be(offset); + + result.Should() + .BeOnOrAfter(utc) + .And + .BeOnOrBefore(utcEnd); + } + + + [Fact] + public void can_set_global_static_time_source() + { + Date.SystemClock = () => DateTime.UtcNow; + + var d = new Date(); + + d.Soon().Kind.Should().Be(DateTimeKind.Utc); + d.Future().Kind.Should().Be(DateTimeKind.Utc); + d.Past().Kind.Should().Be(DateTimeKind.Utc); + d.Recent().Kind.Should().Be(DateTimeKind.Utc); + + d.SoonOffset().Offset.Should().Be(DateTimeOffset.UtcNow.Offset); + d.FutureOffset().Offset.Should().Be(DateTimeOffset.UtcNow.Offset); + d.PastOffset().Offset.Should().Be(DateTimeOffset.UtcNow.Offset); + d.RecentOffset().Offset.Should().Be(DateTimeOffset.UtcNow.Offset); + + Date.SystemClock = () => DateTime.Now; + + d.Soon().Kind.Should().Be(DateTimeKind.Local); + d.Future().Kind.Should().Be(DateTimeKind.Local); + d.Past().Kind.Should().Be(DateTimeKind.Local); + d.Recent().Kind.Should().Be(DateTimeKind.Local); + + d.SoonOffset().Offset.Should().Be(DateTimeOffset.Now.Offset); + d.FutureOffset().Offset.Should().Be(DateTimeOffset.Now.Offset); + d.PastOffset().Offset.Should().Be(DateTimeOffset.Now.Offset); + d.RecentOffset().Offset.Should().Be(DateTimeOffset.Now.Offset); + } + + [Fact] + public void can_get_timezone_string() { - public DateTest() - { - date = new Date(); - } - - private readonly Date date; - - [Fact] - public void can_get_a_random_month() - { - date.Month().Should().NotBeNullOrEmpty(); - date.Month(true).Should().NotBeNullOrEmpty(); - } - - [Fact] - public void can_get_a_random_weekday() - { - date.Weekday().Should().NotBeNullOrEmpty(); - date.Weekday(true).Should().NotBeNullOrEmpty(); - } - - [Fact] - public void can_get_a_timespan() - { - date.Timespan().Should().BePositive() - .And - .BeGreaterThan(TimeSpan.Zero) - .And - .BeLessThan(TimeSpan.FromDays(7)); - } - - - [Fact] - public void can_get_date_in_future() - { - var starting = DateTime.Parse("6/7/2015 4:17:41 PM"); - date.Future(refDate: starting).Should() - .BeOnOrBefore(starting.AddYears(1)) - .And - .BeOnOrAfter(starting); - } - - [Fact] - public void can_get_dateOffset_in_future() - { - var starting = DateTimeOffset.Parse("6/7/2015 4:17:41 PM"); - date.FutureOffset(refDate: starting).Should() - .BeOnOrBefore(starting.AddYears(1)) - .And - .BeOnOrAfter(starting); - } - - [Fact] - public void can_get_date_in_future_with_options() - { - var starting = DateTime.Parse("6/15/2000 4:17:41 PM", CultureInfo.InvariantCulture); - date.Future(refDate: starting, yearsToGoForward: 5).Should() - .BeOnOrBefore(starting.AddYears(5)) - .And - .BeOnOrAfter(starting); - } - - [Fact] - public void can_get_dateOffset_in_future_with_options() - { - var starting = DateTimeOffset.Parse("6/15/2000 4:17:41 PM", CultureInfo.InvariantCulture); - date.FutureOffset(refDate: starting, yearsToGoForward: 5).Should() - .BeOnOrBefore(starting.AddYears(5)) - .And - .BeOnOrAfter(starting); - } - - [Fact] - public void can_get_date_in_past() - { - var starting = DateTime.Parse("6/7/2015 4:17:41 PM"); - date.Past(refDate: starting).Should() - .BeOnOrBefore(starting) - .And - .BeOnOrAfter(starting.AddYears(-1)); - } - - [Fact] - public void can_get_dateOffset_in_past() - { - var starting = DateTimeOffset.Parse("6/7/2015 4:17:41 PM"); - date.PastOffset(refDate: starting).Should() - .BeOnOrBefore(starting) - .And - .BeOnOrAfter(starting.AddYears(-1)); - } - - [Fact] - public void can_get_date_in_past_0_days_results_in_random_time() - { - date.Recent(0).Should() - .BeOnOrBefore(DateTime.Now) - .And - .BeOnOrAfter(DateTime.Now.Date); - } - - [Fact] - public void can_get_dateOffset_in_past_0_days_results_in_random_time() - { - date.RecentOffset(0).Should() - .BeOnOrBefore(DateTimeOffset.Now) - .And - .BeOnOrAfter(DateTimeOffset.Now.Date); - } - - [Fact] - public void can_get_date_in_past_with_custom_options() - { - var starting = DateTime.Parse("6/15/2000 4:17:41 PM", CultureInfo.InvariantCulture); - date.Past(refDate: starting, yearsToGoBack: 5).Should() - .BeOnOrBefore(starting) - .And - .BeOnOrAfter(starting.AddYears(-5)); - } - - [Fact] - public void can_get_dateOffset_in_past_with_custom_options() - { - var starting = DateTimeOffset.Parse("6/15/2000 4:17:41 PM", CultureInfo.InvariantCulture); - date.PastOffset(refDate: starting, yearsToGoBack: 5).Should() - .BeOnOrBefore(starting) - .And - .BeOnOrAfter(starting.AddYears(-5)); - } - - [Fact] - public void can_get_date_recently_within_the_year() - { - var start = DateTime.Now; - date.Recent() - .Should() - .BeOnOrBefore(start) - .And - .BeOnOrAfter(start.AddDays(-1)); - } - - [Fact] - public void can_get_dateOffset_recently_within_the_year() - { - var start = DateTimeOffset.Now; - date.RecentOffset() - .Should() - .BeOnOrBefore(start) - .And - .BeOnOrAfter(start.AddDays(-1)); - } - - [Fact] - public void can_get_random_time_between_two_dates() - { - var start = DateTime.Parse("6/15/2000 4:17:41 PM", CultureInfo.InvariantCulture); - var end = DateTime.Parse("8/15/2000 4:17:41 PM", CultureInfo.InvariantCulture); - - date.Between(start, end) - .Should() - .BeOnOrAfter(start) - .And - .BeOnOrBefore(end); - - //and reverse... - date.Between(end, start) - .Should() - .BeOnOrAfter(start) - .And - .BeOnOrBefore(end); - } - - [Fact] - public void can_get_random_time_between_two_dateOffsets() - { - var start = DateTimeOffset.Parse("6/15/2000 4:17:41 PM", CultureInfo.InvariantCulture); - var end = DateTimeOffset.Parse("8/15/2000 4:17:41 PM", CultureInfo.InvariantCulture); - - date.BetweenOffset(start, end) - .Should() - .BeOnOrAfter(start) - .And - .BeOnOrBefore(end); - - //and reverse... - date.BetweenOffset(end, start) - .Should() - .BeOnOrAfter(start) - .And - .BeOnOrBefore(end); - } - - [Fact] - public void get_a_date_that_will_happen_soon() - { - var now = DateTime.Now; - date.Soon(3).Should().BeAfter(now).And.BeBefore(now.AddDays(3)); - } - - [Fact] - public void get_a_dateOffsets_that_will_happen_soon() - { - var now = DateTimeOffset.Now; - date.SoonOffset(3).Should().BeAfter(now).And.BeBefore(now.AddDays(3)); - } - - [Fact] - public void soon_explicit_refdate_in_utc_should_return_utc_kind() - { - const int days = 3; - var dt = DateTime.Parse("7/5/2018 9:00 AM"); - var utc = DateTime.SpecifyKind(dt, DateTimeKind.Utc); - var utcEnd = utc.AddDays(days); - var result = date.Soon(days, utc); - - result.Kind.Should().Be(DateTimeKind.Utc); - - result.Should() - .BeOnOrAfter(utc) - .And - .BeOnOrBefore(utcEnd); - } - - [Fact] - public void soon_explicit_refdate_offset_should_return_explicit_offset() - { - const int days = 3; - var offset = TimeSpan.FromHours(-3); - var utc = DateTimeOffset.Parse("7/5/2018 9:00 AM").ToOffset(offset); - var utcEnd = utc.AddDays(days); - var result = date.SoonOffset(days, utc); - - result.Offset.Should().Be(offset); - - result.Should() - .BeOnOrAfter(utc) - .And - .BeOnOrBefore(utcEnd); - } - - [Fact] - public void recent_explicit_refdate_in_utc_should_return_utc_kind() - { - const int days = 3; - var dt = DateTime.Parse("7/5/2018 9:00 AM"); - var utcEnd = DateTime.SpecifyKind(dt, DateTimeKind.Utc); - var utcPast = utcEnd.AddDays(-days); - var result = date.Recent(days, utcEnd); - - result.Kind.Should().Be(DateTimeKind.Utc); - - result.Should() - .BeOnOrAfter(utcPast) - .And - .BeOnOrBefore(utcEnd); - } - - [Fact] - public void recent_explicit_refdate_offset_should_return_explicit_offset() - { - const int days = 3; - var offset = TimeSpan.FromHours(-3); - var utcEnd = DateTimeOffset.Parse("7/5/2018 9:00 AM").ToOffset(offset); - var utcPast = utcEnd.AddDays(-days); - var result = date.RecentOffset(days, utcEnd); - - result.Offset.Should().Be(offset); - - result.Should() - .BeOnOrAfter(utcPast) - .And - .BeOnOrBefore(utcEnd); - } - - [Fact] - public void between_explicit_refdate_in_utc_should_return_utc_kind() - { - const int days = 3; - var dt = DateTime.Parse("8/8/2017 10:00 AM"); - var utc = DateTime.SpecifyKind(dt, DateTimeKind.Utc); - var utcEnd = utc.AddDays(days); - var result = date.Between(utc, utcEnd); - - result.Kind.Should().Be(DateTimeKind.Utc); - - result.Should() - .BeOnOrAfter(utc) - .And - .BeOnOrBefore(utcEnd); - } - - [Fact] - public void between_explicit_start_offset_should_return_explicit_offset() - { - const int days = 3; - var offset = TimeSpan.FromHours(-3); - var utc = DateTimeOffset.Parse("8/8/2017 10:00 AM").ToOffset(offset); - var utcEnd = utc.AddDays(days); - var result = date.BetweenOffset(utc, utcEnd); - - result.Offset.Should().Be(offset); - - result.Should() - .BeOnOrAfter(utc) - .And - .BeOnOrBefore(utcEnd); - } - - - [Fact] - public void can_set_global_static_time_source() - { - Date.SystemClock = () => DateTime.UtcNow; - - var d = new Date(); - - d.Soon().Kind.Should().Be(DateTimeKind.Utc); - d.Future().Kind.Should().Be(DateTimeKind.Utc); - d.Past().Kind.Should().Be(DateTimeKind.Utc); - d.Recent().Kind.Should().Be(DateTimeKind.Utc); - - d.SoonOffset().Offset.Should().Be(DateTimeOffset.UtcNow.Offset); - d.FutureOffset().Offset.Should().Be(DateTimeOffset.UtcNow.Offset); - d.PastOffset().Offset.Should().Be(DateTimeOffset.UtcNow.Offset); - d.RecentOffset().Offset.Should().Be(DateTimeOffset.UtcNow.Offset); - - Date.SystemClock = () => DateTime.Now; - - d.Soon().Kind.Should().Be(DateTimeKind.Local); - d.Future().Kind.Should().Be(DateTimeKind.Local); - d.Past().Kind.Should().Be(DateTimeKind.Local); - d.Recent().Kind.Should().Be(DateTimeKind.Local); - - d.SoonOffset().Offset.Should().Be(DateTimeOffset.Now.Offset); - d.FutureOffset().Offset.Should().Be(DateTimeOffset.Now.Offset); - d.PastOffset().Offset.Should().Be(DateTimeOffset.Now.Offset); - d.RecentOffset().Offset.Should().Be(DateTimeOffset.Now.Offset); - } - - [Fact] - public void can_get_timezone_string() - { - date.TimeZoneString().Should().Be("Asia/Yerevan"); - } + date.TimeZoneString().Should().Be("Asia/Yerevan"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/DataSetTests/DateTest.net60.cs b/Source/Bogus.Tests/DataSetTests/DateTest.net60.cs index 910ae264..1c11a020 100644 --- a/Source/Bogus.Tests/DataSetTests/DateTest.net60.cs +++ b/Source/Bogus.Tests/DataSetTests/DateTest.net60.cs @@ -4,136 +4,135 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.DataSetTests +namespace Bogus.Tests.DataSetTests; + +public partial class DateTest { - public partial class DateTest - { #if NET6_0 - [Fact] - public void can_get_dateonly_in_past() - { - var now = DateOnly.Parse("7/7/1972", CultureInfo.InvariantCulture); - var maxBehind = now.AddYears(-1); - - var somePastDate = date.PastDateOnly(refDate: now); - somePastDate.Should().BeOnOrAfter(maxBehind).And.BeOnOrBefore(now); - } - - [Fact] - public void can_get_dateonly_in_past_with_custom_options() - { - var now = DateOnly.Parse("7/7/1972", CultureInfo.InvariantCulture); - var maxBehind = now.AddYears(-5); - - var somePastDate = date.PastDateOnly(5, now); - - somePastDate.Should().BeOnOrAfter(maxBehind).And.BeOnOrBefore(now); - } - - [Fact] - public void get_a_dateonly_that_will_happen_soon() - { - var now = DateOnly.Parse("7/7/1972", CultureInfo.InvariantCulture); - var maxDate = now.AddDays(3); - - var someDateSoon = date.SoonDateOnly(3, now); - - someDateSoon.Should().BeOnOrAfter(now).And.BeOnOrBefore(maxDate); - } - - [Fact] - public void can_get_dateonly_in_future() - { - var now = DateOnly.Parse("1/1/1990", CultureInfo.InvariantCulture); - var maxDate = now.AddYears(1); - - var someFutureDate = date.FutureDateOnly(refDate: now); - someFutureDate.Should().BeOnOrAfter(now).And.BeOnOrBefore(maxDate); - } - - [Fact] - public void can_get_dateonly_in_future_with_options() - { - var now = DateOnly.Parse("7/7/1972", CultureInfo.InvariantCulture); - var maxDate = now.AddYears(5); - - var someFutureDate = date.FutureDateOnly(5, now); - someFutureDate.Should().BeOnOrAfter(now).And.BeOnOrBefore(maxDate); - } - - [Fact] - public void can_get_random_dateonly_between_two_dates() - { - var start = DateOnly.Parse("8/8/2020", CultureInfo.InvariantCulture); - var end = DateOnly.Parse("12/12/2021", CultureInfo.InvariantCulture); - - var someDate = date.BetweenDateOnly(start, end); - - someDate.Should().BeOnOrAfter(start).And.BeOnOrBefore(end); - - //and reverse... - var otherDate = date.BetweenDateOnly(end, start); - otherDate.Should().BeOnOrAfter(start).And.BeOnOrBefore(end); - } - - [Fact] - public void can_get_dateonly_recently_within_the_year() - { - var now = DateOnly.Parse("7/7/1972", CultureInfo.InvariantCulture); - var maxBehind = now.AddDays(-1); - - var someRecentDate = date.RecentDateOnly(refDate: now); - - someRecentDate.Should().BeOnOrAfter(maxBehind).And.BeOnOrBefore(now); - } - - [Fact] - public void can_get_random_timeonly_between_two_times_basic() - { - var start = TimeOnly.Parse("1:00 PM", CultureInfo.InvariantCulture); - var end = TimeOnly.Parse("2:00 PM", CultureInfo.InvariantCulture); - - var someTimeBetween = date.BetweenTimeOnly(start, end); - someTimeBetween.IsBetween(start, end).Should().BeTrue(); - - var outside = TimeOnly.Parse("2:30 PM", CultureInfo.InvariantCulture); - outside.IsBetween(start, end).Should().BeFalse(); - } - - [Fact] - public void can_get_random_timeonly_between_two_times_wrap_around() - { - //wrap around from 2:00 PM to 1:00 PM; times from 1:00 PM -> 2:00 PM is excluded. - var start = TimeOnly.Parse("2:00 PM", CultureInfo.InvariantCulture); - var end = TimeOnly.Parse("1:00 PM", CultureInfo.InvariantCulture); - - var someTimeBetween = date.BetweenTimeOnly(end, start); - someTimeBetween.IsBetween(end, start).Should().BeTrue(); - - var outside = TimeOnly.Parse("1:30 PM", CultureInfo.InvariantCulture); - outside.IsBetween(start, end).Should().BeFalse(); - } - - [Fact] - public void can_get_a_timeonly_that_will_happen_soon() - { - var now = TimeOnly.Parse("1:00 PM", CultureInfo.InvariantCulture); - var maxTime = now.AddMinutes(5); - - var timeSoon = date.SoonTimeOnly(5, now); - - timeSoon.IsBetween(now, maxTime).Should().BeTrue(); - } + [Fact] + public void can_get_dateonly_in_past() + { + var now = DateOnly.Parse("7/7/1972", CultureInfo.InvariantCulture); + var maxBehind = now.AddYears(-1); - [Fact] - public void can_get_a_timeonly_that_happened_recently() - { - var now = TimeOnly.Parse("2:00 PM", CultureInfo.InvariantCulture); - var maxBehind = now.AddMinutes(-5); - - var timeRecent = date.RecentTimeOnly(5, now); - timeRecent.IsBetween(maxBehind, now).Should().BeTrue(); - } -#endif + var somePastDate = date.PastDateOnly(refDate: now); + somePastDate.Should().BeOnOrAfter(maxBehind).And.BeOnOrBefore(now); + } + + [Fact] + public void can_get_dateonly_in_past_with_custom_options() + { + var now = DateOnly.Parse("7/7/1972", CultureInfo.InvariantCulture); + var maxBehind = now.AddYears(-5); + + var somePastDate = date.PastDateOnly(5, now); + + somePastDate.Should().BeOnOrAfter(maxBehind).And.BeOnOrBefore(now); + } + + [Fact] + public void get_a_dateonly_that_will_happen_soon() + { + var now = DateOnly.Parse("7/7/1972", CultureInfo.InvariantCulture); + var maxDate = now.AddDays(3); + + var someDateSoon = date.SoonDateOnly(3, now); + + someDateSoon.Should().BeOnOrAfter(now).And.BeOnOrBefore(maxDate); } + + [Fact] + public void can_get_dateonly_in_future() + { + var now = DateOnly.Parse("1/1/1990", CultureInfo.InvariantCulture); + var maxDate = now.AddYears(1); + + var someFutureDate = date.FutureDateOnly(refDate: now); + someFutureDate.Should().BeOnOrAfter(now).And.BeOnOrBefore(maxDate); + } + + [Fact] + public void can_get_dateonly_in_future_with_options() + { + var now = DateOnly.Parse("7/7/1972", CultureInfo.InvariantCulture); + var maxDate = now.AddYears(5); + + var someFutureDate = date.FutureDateOnly(5, now); + someFutureDate.Should().BeOnOrAfter(now).And.BeOnOrBefore(maxDate); + } + + [Fact] + public void can_get_random_dateonly_between_two_dates() + { + var start = DateOnly.Parse("8/8/2020", CultureInfo.InvariantCulture); + var end = DateOnly.Parse("12/12/2021", CultureInfo.InvariantCulture); + + var someDate = date.BetweenDateOnly(start, end); + + someDate.Should().BeOnOrAfter(start).And.BeOnOrBefore(end); + + //and reverse... + var otherDate = date.BetweenDateOnly(end, start); + otherDate.Should().BeOnOrAfter(start).And.BeOnOrBefore(end); + } + + [Fact] + public void can_get_dateonly_recently_within_the_year() + { + var now = DateOnly.Parse("7/7/1972", CultureInfo.InvariantCulture); + var maxBehind = now.AddDays(-1); + + var someRecentDate = date.RecentDateOnly(refDate: now); + + someRecentDate.Should().BeOnOrAfter(maxBehind).And.BeOnOrBefore(now); + } + + [Fact] + public void can_get_random_timeonly_between_two_times_basic() + { + var start = TimeOnly.Parse("1:00 PM", CultureInfo.InvariantCulture); + var end = TimeOnly.Parse("2:00 PM", CultureInfo.InvariantCulture); + + var someTimeBetween = date.BetweenTimeOnly(start, end); + someTimeBetween.IsBetween(start, end).Should().BeTrue(); + + var outside = TimeOnly.Parse("2:30 PM", CultureInfo.InvariantCulture); + outside.IsBetween(start, end).Should().BeFalse(); + } + + [Fact] + public void can_get_random_timeonly_between_two_times_wrap_around() + { + //wrap around from 2:00 PM to 1:00 PM; times from 1:00 PM -> 2:00 PM is excluded. + var start = TimeOnly.Parse("2:00 PM", CultureInfo.InvariantCulture); + var end = TimeOnly.Parse("1:00 PM", CultureInfo.InvariantCulture); + + var someTimeBetween = date.BetweenTimeOnly(end, start); + someTimeBetween.IsBetween(end, start).Should().BeTrue(); + + var outside = TimeOnly.Parse("1:30 PM", CultureInfo.InvariantCulture); + outside.IsBetween(start, end).Should().BeFalse(); + } + + [Fact] + public void can_get_a_timeonly_that_will_happen_soon() + { + var now = TimeOnly.Parse("1:00 PM", CultureInfo.InvariantCulture); + var maxTime = now.AddMinutes(5); + + var timeSoon = date.SoonTimeOnly(5, now); + + timeSoon.IsBetween(now, maxTime).Should().BeTrue(); + } + + [Fact] + public void can_get_a_timeonly_that_happened_recently() + { + var now = TimeOnly.Parse("2:00 PM", CultureInfo.InvariantCulture); + var maxBehind = now.AddMinutes(-5); + + var timeRecent = date.RecentTimeOnly(5, now); + timeRecent.IsBetween(maxBehind, now).Should().BeTrue(); + } +#endif } diff --git a/Source/Bogus.Tests/DataSetTests/FinanceTest.cs b/Source/Bogus.Tests/DataSetTests/FinanceTest.cs index b6ec8389..d954fbcf 100644 --- a/Source/Bogus.Tests/DataSetTests/FinanceTest.cs +++ b/Source/Bogus.Tests/DataSetTests/FinanceTest.cs @@ -5,193 +5,192 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.DataSetTests +namespace Bogus.Tests.DataSetTests; + +public class FinanceTest : SeededTest { - public class FinanceTest : SeededTest - { - public FinanceTest() - { - finance = new Finance(); - } - - private readonly Finance finance; - - [Fact] - public void can_get_a_random_account_default() - { - finance.Account().Should().Be("61860606"); - } - - [Fact] - public void can_get_a_random_account_12() - { - finance.Account(12).Should().Be("618606064391"); - } - - [Fact] - public void can_get_a_random_account_name() - { - finance.AccountName().Should().Be("Home Loan Account"); - } - - [Fact] - public void can_generate_a_random_bitcoin_address() - { - var btc = finance.BitcoinAddress(); - btc.Should().MatchRegex("^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$"); - btc.Should().Be("17PE5D8HxpXjM3igcWbTeyKns2YdAfLC"); - } - - [Fact] - public void can_generate_a_random_ethereum_address() - { - finance.EthereumAddress().Should().Be("0x91da090b74f2b910be0dd5991af6398351ac2ef3"); - } - - [Fact] - public void can_generate_a_random_litecoin_address() - { - finance.LitecoinAddress().Should().Be("L7PE5D8HxpXjM3igcWbTeyKns2YdAfL"); - } - - [Fact] - public void can_generate_aba_routing_number() - { - finance.RoutingNumber().Should().Be("618606061"); - } - - [Fact] - public void can_generate_bic() - { - finance.Bic().Should().Be("CVQAMUB1"); - } - - [Fact] - public void can_generate_iban() - { - finance.Iban().Should().Be("MT78CVQA0491707AV6092536EZ69UM5"); - - finance.Iban(true).Should().Be("BH95 LCFH 2236 87QH UU47 F6"); - } - - [Fact] - public void can_generate_iban2() - { - finance.Iban(countryCode: "ro").Should().Be("RO36PCVQ663E5098I56K5218"); - finance.Iban(countryCode: "sa", formatted: true).Should().Be("SA90 19G4 X820 1322 3687 QHUU"); - } - - [Fact] - public void iban_throws_key_not_found_on_invalid_iso3166() - { - Action a = () => finance.Iban(countryCode: "zz"); - a.Should().Throw(); - } - - [Fact] - public void iban_thows_on_invalid_iso3166_length() - { - Action a = () => finance.Iban(countryCode: "fff"); - a.Should().Throw(); - } - - [Fact] - public void can_get_random_currency() - { - var cur = finance.Currency(); - - cur.Description.Should().Be("Nepalese Rupee"); - cur.Code.Should().Be("NPR"); - cur.Symbol.Should().NotBeNullOrWhiteSpace(); - } - - [Fact] - public void get_random_amount() - { - finance.Amount().Should().Be(603.52m); - } - - [Fact] - public void get_random_amount_with_options() - { - var val = finance.Amount(200, 300, 3); - - val.Should() - .BeInRange(200, 300); - - //get decimal places. - var decimals = BitConverter.GetBytes(decimal.GetBits(val)[3])[2]; - - decimals.Should().Be(3); - } - - [Fact] - public void get_random_amount_with_zero_decimals() - { - finance.Amount(decimals: 0).Should().Be(604); - } - - [Fact] - public void should_be_able_to_get_a_transaction_type() - { - finance.TransactionType().Should().Be("payment"); - } - - [Fact] - public void can_get_random_credit_card_number() - { - finance.CreditCardNumber(CardType.Switch) - .Should().Be("6759-1860-6064-3917-52") - .And.Match(f => Luhn(f)); - finance.CreditCardNumber(CardType.AmericanExpress) - .Should().Be("3407-908836-50694") - .And.Match(f => Luhn(f)); - finance.CreditCardNumber(CardType.Instapayment) - .Should().Be("6375-5231-6819-9268") - .And.Match(f => Luhn(f)); - finance.CreditCardNumber(CardType.Maestro) - .Should().Be("6759-9878-4250-4118") - .And.Match(f => Luhn(f)); - finance.CreditCardNumber(CardType.Jcb) - .Should().Be("3528-1242-5366-4879") - .And.Match(f => Luhn(f)); - finance.CreditCardNumber(CardType.Visa) - .Should().Be("4869-2879-7143-7822") - .And.Match(f => Luhn(f)); - finance.CreditCardNumber(CardType.Mastercard) - .Should().Be("5481-1400-9339-3651") - .And.Match(f => Luhn(f)); - finance.CreditCardNumber(CardType.Solo) - .Should().Be("6767-9010-0832-1613-169") - .And.Match(f => Luhn(f)); - finance.CreditCardNumber(CardType.DinersClub) - .Should().Be("5474-3198-2736-8655") - .And.Match(f => Luhn(f)); - finance.CreditCardNumber(CardType.Discover) - .Should().Be("6493-6232-2435-7233-5952") - .And.Match(f => Luhn(f)); - finance.CreditCardNumber(CardType.Laser) - .Should().Be("6771693455045167") - .And.Match(f => Luhn(f)); - - finance.CreditCardNumber().Should().Be("3731-282228-18252") - .And.Match(f => Luhn(f)); - } - - [Fact] - public void can_get_random_credit_card_cvv() - { - finance.CreditCardCvv().Should().Be("618"); - } - - private static bool Luhn(string digits) - { - return digits.Where(char.IsDigit).Reverse() - .Select(c => c - 48) - .Select((thisNum, i) => i % 2 == 0 - ? thisNum - : ((thisNum *= 2) > 9 ? thisNum - 9 : thisNum) - ).Sum() % 10 == 0; - } + public FinanceTest() + { + finance = new Finance(); + } + + private readonly Finance finance; + + [Fact] + public void can_get_a_random_account_default() + { + finance.Account().Should().Be("61860606"); + } + + [Fact] + public void can_get_a_random_account_12() + { + finance.Account(12).Should().Be("618606064391"); + } + + [Fact] + public void can_get_a_random_account_name() + { + finance.AccountName().Should().Be("Home Loan Account"); + } + + [Fact] + public void can_generate_a_random_bitcoin_address() + { + var btc = finance.BitcoinAddress(); + btc.Should().MatchRegex("^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$"); + btc.Should().Be("17PE5D8HxpXjM3igcWbTeyKns2YdAfLC"); + } + + [Fact] + public void can_generate_a_random_ethereum_address() + { + finance.EthereumAddress().Should().Be("0x91da090b74f2b910be0dd5991af6398351ac2ef3"); + } + + [Fact] + public void can_generate_a_random_litecoin_address() + { + finance.LitecoinAddress().Should().Be("L7PE5D8HxpXjM3igcWbTeyKns2YdAfL"); + } + + [Fact] + public void can_generate_aba_routing_number() + { + finance.RoutingNumber().Should().Be("618606061"); + } + + [Fact] + public void can_generate_bic() + { + finance.Bic().Should().Be("CVQAMUB1"); + } + + [Fact] + public void can_generate_iban() + { + finance.Iban().Should().Be("MT78CVQA0491707AV6092536EZ69UM5"); + + finance.Iban(true).Should().Be("BH95 LCFH 2236 87QH UU47 F6"); + } + + [Fact] + public void can_generate_iban2() + { + finance.Iban(countryCode: "ro").Should().Be("RO36PCVQ663E5098I56K5218"); + finance.Iban(countryCode: "sa", formatted: true).Should().Be("SA90 19G4 X820 1322 3687 QHUU"); + } + + [Fact] + public void iban_throws_key_not_found_on_invalid_iso3166() + { + Action a = () => finance.Iban(countryCode: "zz"); + a.Should().Throw(); + } + + [Fact] + public void iban_thows_on_invalid_iso3166_length() + { + Action a = () => finance.Iban(countryCode: "fff"); + a.Should().Throw(); + } + + [Fact] + public void can_get_random_currency() + { + var cur = finance.Currency(); + + cur.Description.Should().Be("Nepalese Rupee"); + cur.Code.Should().Be("NPR"); + cur.Symbol.Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public void get_random_amount() + { + finance.Amount().Should().Be(603.52m); + } + + [Fact] + public void get_random_amount_with_options() + { + var val = finance.Amount(200, 300, 3); + + val.Should() + .BeInRange(200, 300); + + //get decimal places. + var decimals = BitConverter.GetBytes(decimal.GetBits(val)[3])[2]; + + decimals.Should().Be(3); + } + + [Fact] + public void get_random_amount_with_zero_decimals() + { + finance.Amount(decimals: 0).Should().Be(604); + } + + [Fact] + public void should_be_able_to_get_a_transaction_type() + { + finance.TransactionType().Should().Be("payment"); + } + + [Fact] + public void can_get_random_credit_card_number() + { + finance.CreditCardNumber(CardType.Switch) + .Should().Be("6759-1860-6064-3917-52") + .And.Match(f => Luhn(f)); + finance.CreditCardNumber(CardType.AmericanExpress) + .Should().Be("3407-908836-50694") + .And.Match(f => Luhn(f)); + finance.CreditCardNumber(CardType.Instapayment) + .Should().Be("6375-5231-6819-9268") + .And.Match(f => Luhn(f)); + finance.CreditCardNumber(CardType.Maestro) + .Should().Be("6759-9878-4250-4118") + .And.Match(f => Luhn(f)); + finance.CreditCardNumber(CardType.Jcb) + .Should().Be("3528-1242-5366-4879") + .And.Match(f => Luhn(f)); + finance.CreditCardNumber(CardType.Visa) + .Should().Be("4869-2879-7143-7822") + .And.Match(f => Luhn(f)); + finance.CreditCardNumber(CardType.Mastercard) + .Should().Be("5481-1400-9339-3651") + .And.Match(f => Luhn(f)); + finance.CreditCardNumber(CardType.Solo) + .Should().Be("6767-9010-0832-1613-169") + .And.Match(f => Luhn(f)); + finance.CreditCardNumber(CardType.DinersClub) + .Should().Be("5474-3198-2736-8655") + .And.Match(f => Luhn(f)); + finance.CreditCardNumber(CardType.Discover) + .Should().Be("6493-6232-2435-7233-5952") + .And.Match(f => Luhn(f)); + finance.CreditCardNumber(CardType.Laser) + .Should().Be("6771693455045167") + .And.Match(f => Luhn(f)); + + finance.CreditCardNumber().Should().Be("3731-282228-18252") + .And.Match(f => Luhn(f)); + } + + [Fact] + public void can_get_random_credit_card_cvv() + { + finance.CreditCardCvv().Should().Be("618"); + } + + private static bool Luhn(string digits) + { + return digits.Where(char.IsDigit).Reverse() + .Select(c => c - 48) + .Select((thisNum, i) => i % 2 == 0 + ? thisNum + : ((thisNum *= 2) > 9 ? thisNum - 9 : thisNum) + ).Sum() % 10 == 0; } } diff --git a/Source/Bogus.Tests/DataSetTests/HackerTests.cs b/Source/Bogus.Tests/DataSetTests/HackerTests.cs index 4731f51e..f0e0b314 100644 --- a/Source/Bogus.Tests/DataSetTests/HackerTests.cs +++ b/Source/Bogus.Tests/DataSetTests/HackerTests.cs @@ -2,31 +2,30 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.DataSetTests +namespace Bogus.Tests.DataSetTests; + +public class HackerTests : SeededTest { - public class HackerTests : SeededTest + public HackerTests() { - public HackerTests() - { - hacker = new Hacker(); - } + hacker = new Hacker(); + } - private readonly Hacker hacker; + private readonly Hacker hacker; - [Fact] - public void can_get_a_hacker_phrase() - { - hacker.Phrase().Should().Be("Use the neural RAM driver, then you can calculate the neural driver!"); - } + [Fact] + public void can_get_a_hacker_phrase() + { + hacker.Phrase().Should().Be("Use the neural RAM driver, then you can calculate the neural driver!"); + } - [Fact] - public void make_sure_we_have_updated_ru_hacker_locale() - { - var ruhacker = new Hacker("ru"); - ruhacker.Adjective().Should().Be("многобайтный"); - ruhacker.Noun().Should().Be("ограничитель"); - ruhacker.Verb().Should().Be("ввести"); - ruhacker.IngVerb().Should().Be("генерация"); - } + [Fact] + public void make_sure_we_have_updated_ru_hacker_locale() + { + var ruhacker = new Hacker("ru"); + ruhacker.Adjective().Should().Be("многобайтный"); + ruhacker.Noun().Should().Be("ограничитель"); + ruhacker.Verb().Should().Be("ввести"); + ruhacker.IngVerb().Should().Be("генерация"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/DataSetTests/ImageTest.cs b/Source/Bogus.Tests/DataSetTests/ImageTest.cs index ddeec767..5417751f 100644 --- a/Source/Bogus.Tests/DataSetTests/ImageTest.cs +++ b/Source/Bogus.Tests/DataSetTests/ImageTest.cs @@ -6,43 +6,43 @@ using Xunit.Abstractions; using static Bogus.DataSets.LoremPixelCategory; -namespace Bogus.Tests.DataSetTests +namespace Bogus.Tests.DataSetTests; + +public class ImageTest : SeededTest { - public class ImageTest : SeededTest + private readonly ITestOutputHelper console; + + public ImageTest(ITestOutputHelper console) + { + this.console = console; + image = new Images(); + } + + private readonly Images image; + + [Fact(Skip = "Explicit")] + public void DownloadAllTest() { - private readonly ITestOutputHelper console; - - public ImageTest(ITestOutputHelper console) - { - this.console = console; - image = new Images(); - } - - private readonly Images image; - - [Fact(Skip = "Explicit")] - public void DownloadAllTest() - { - var wc = new WebClient(); - wc.DownloadFile(image.LoremPixelUrl(Abstract), "abstract.jpg"); - wc.DownloadFile(image.LoremPixelUrl(Animals), "animals.jpg"); - wc.DownloadFile(image.LoremPixelUrl(Business), "business.jpg"); - wc.DownloadFile(image.LoremPixelUrl(Cats), "cats.jpg"); - wc.DownloadFile(image.LoremPixelUrl(City), "city.jpg"); - wc.DownloadFile(image.LoremPixelUrl(Food), "food.jpg"); - wc.DownloadFile(image.LoremPixelUrl(Nightlife), "nightlife.jpg"); - wc.DownloadFile(image.LoremPixelUrl(Fashion), "fashion.jpg"); - wc.DownloadFile(image.LoremPixelUrl(People), "people.jpg"); - wc.DownloadFile(image.LoremPixelUrl(Nature), "nature.jpg"); - wc.DownloadFile(image.LoremPixelUrl(Sports), "sports.jpg"); - wc.DownloadFile(image.LoremPixelUrl(Technics), "technics.jpg"); - wc.DownloadFile(image.LoremPixelUrl(Transport), "transport.jpg"); - } - - [Fact] - public void svg_data_url() - { - var html = @" + var wc = new WebClient(); + wc.DownloadFile(image.LoremPixelUrl(Abstract), "abstract.jpg"); + wc.DownloadFile(image.LoremPixelUrl(Animals), "animals.jpg"); + wc.DownloadFile(image.LoremPixelUrl(Business), "business.jpg"); + wc.DownloadFile(image.LoremPixelUrl(Cats), "cats.jpg"); + wc.DownloadFile(image.LoremPixelUrl(City), "city.jpg"); + wc.DownloadFile(image.LoremPixelUrl(Food), "food.jpg"); + wc.DownloadFile(image.LoremPixelUrl(Nightlife), "nightlife.jpg"); + wc.DownloadFile(image.LoremPixelUrl(Fashion), "fashion.jpg"); + wc.DownloadFile(image.LoremPixelUrl(People), "people.jpg"); + wc.DownloadFile(image.LoremPixelUrl(Nature), "nature.jpg"); + wc.DownloadFile(image.LoremPixelUrl(Sports), "sports.jpg"); + wc.DownloadFile(image.LoremPixelUrl(Technics), "technics.jpg"); + wc.DownloadFile(image.LoremPixelUrl(Transport), "transport.jpg"); + } + + [Fact] + public void svg_data_url() + { + var html = @" @@ -53,95 +53,94 @@ public void svg_data_url() "; - var dataUri = image.DataUri(200, 300, "red"); - - console.Dump(dataUri); - var content = html.Replace("{imgdata}", dataUri); - var filename = Path.ChangeExtension(Path.GetRandomFileName(), "html"); - var file = Path.Combine(Path.GetTempPath(), filename); - File.WriteAllText(file, content); - console.Dump(file); - - image.DataUri(200, 300).Should() - .Be( - "data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20version%3D%221.1%22%20baseProfile%3D%22full%22%20width%3D%22200%22%20height%3D%22300%22%3E%3Crect%20width%3D%22100%25%22%20height%3D%22100%25%22%20fill%3D%22grey%22%2F%3E%3Ctext%20x%3D%22100%22%20y%3D%22150%22%20font-size%3D%2220%22%20alignment-baseline%3D%22middle%22%20text-anchor%3D%22middle%22%20fill%3D%22white%22%3E200x300%3C%2Ftext%3E%3C%2Fsvg%3E"); - } + var dataUri = image.DataUri(200, 300, "red"); + + console.Dump(dataUri); + var content = html.Replace("{imgdata}", dataUri); + var filename = Path.ChangeExtension(Path.GetRandomFileName(), "html"); + var file = Path.Combine(Path.GetTempPath(), filename); + File.WriteAllText(file, content); + console.Dump(file); + + image.DataUri(200, 300).Should() + .Be( + "data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20version%3D%221.1%22%20baseProfile%3D%22full%22%20width%3D%22200%22%20height%3D%22300%22%3E%3Crect%20width%3D%22100%25%22%20height%3D%22100%25%22%20fill%3D%22grey%22%2F%3E%3Ctext%20x%3D%22100%22%20y%3D%22150%22%20font-size%3D%2220%22%20alignment-baseline%3D%22middle%22%20text-anchor%3D%22middle%22%20fill%3D%22white%22%3E200x300%3C%2Ftext%3E%3C%2Fsvg%3E"); + } - [Fact] - public void url_generated_should_have_https() - { - image.LoremPixelUrl(Sports, https: true).Should().StartWith("https://"); - } + [Fact] + public void url_generated_should_have_https() + { + image.LoremPixelUrl(Sports, https: true).Should().StartWith("https://"); + } - [Fact] - public void can_use_picsum_Url() - { - var url = image.PicsumUrl(200, 300); - url.Should().Be("https://picsum.photos/200/300/?image=654"); + [Fact] + public void can_use_picsum_Url() + { + var url = image.PicsumUrl(200, 300); + url.Should().Be("https://picsum.photos/200/300/?image=654"); - url = image.PicsumUrl(300, 200, true, true); - url.Should().Be("https://picsum.photos/g/300/200/?image=119&blur"); - } + url = image.PicsumUrl(300, 200, true, true); + url.Should().Be("https://picsum.photos/g/300/200/?image=119&blur"); + } - [Fact] - public void can_use_placeholder_url() - { - var url = image.PlaceholderUrl(200, 300, "foobar is today", "090", "ddd"); - url.Should().Be("https://via.placeholder.com/200x300/090/ddd.png?text=foobar%20is%20today"); + [Fact] + public void can_use_placeholder_url() + { + var url = image.PlaceholderUrl(200, 300, "foobar is today", "090", "ddd"); + url.Should().Be("https://via.placeholder.com/200x300/090/ddd.png?text=foobar%20is%20today"); - url = image.PlaceholderUrl(300, 200); - url.Should().Be("https://via.placeholder.com/300x200/cccccc/9c9c9c.png"); - } + url = image.PlaceholderUrl(300, 200); + url.Should().Be("https://via.placeholder.com/300x200/cccccc/9c9c9c.png"); + } - [Fact] - public void can_use_loremflickr() - { - var img = image.LoremFlickrUrl(640, 480, "dog"); + [Fact] + public void can_use_loremflickr() + { + var img = image.LoremFlickrUrl(640, 480, "dog"); - img.Should().Be("https://loremflickr.com/640/480/dog/any?lock=1721768941"); - - img = image.LoremFlickrUrl(100, 100, "cat"); + img.Should().Be("https://loremflickr.com/640/480/dog/any?lock=1721768941"); + + img = image.LoremFlickrUrl(100, 100, "cat"); - img.Should().Be("https://loremflickr.com/100/100/cat/any?lock=199070641"); + img.Should().Be("https://loremflickr.com/100/100/cat/any?lock=199070641"); - img = image.LoremFlickrUrl(100, 100, "cat,bird"); + img = image.LoremFlickrUrl(100, 100, "cat,bird"); - img.Should().Be("https://loremflickr.com/100/100/cat,bird/any?lock=1035518479"); + img.Should().Be("https://loremflickr.com/100/100/cat,bird/any?lock=1035518479"); - img = image.LoremFlickrUrl(100, 100, "cat,bird", lockId: -1, grascale: true); + img = image.LoremFlickrUrl(100, 100, "cat,bird", lockId: -1, grascale: true); - img.Should().Be("https://loremflickr.com/g/100/100/cat,bird/any"); + img.Should().Be("https://loremflickr.com/g/100/100/cat,bird/any"); - img = image.LoremFlickrUrl(100, 100, "cat bird", lockId: -1, grascale: true, matchAllKeywords:true); + img = image.LoremFlickrUrl(100, 100, "cat bird", lockId: -1, grascale: true, matchAllKeywords:true); - img.Should().Be("https://loremflickr.com/g/100/100/cat,bird/all"); + img.Should().Be("https://loremflickr.com/g/100/100/cat,bird/all"); - img = image.LoremFlickrUrl(100, 100, "cat bird", lockId: 227, grascale: true, matchAllKeywords: true); + img = image.LoremFlickrUrl(100, 100, "cat bird", lockId: 227, grascale: true, matchAllKeywords: true); - img.Should().Be("https://loremflickr.com/g/100/100/cat,bird/all?lock=227"); - } + img.Should().Be("https://loremflickr.com/g/100/100/cat,bird/all?lock=227"); + } - [Fact] - public void can_use_placeimg_url() - { - var img = image.PlaceImgUrl(640, 480, PlaceImgCategory.Animals); - img.Should().Be("https://placeimg.com/640/480/animals"); + [Fact] + public void can_use_placeimg_url() + { + var img = image.PlaceImgUrl(640, 480, PlaceImgCategory.Animals); + img.Should().Be("https://placeimg.com/640/480/animals"); - img = image.PlaceImgUrl(); - img.Should().Be("https://placeimg.com/640/480/any"); + img = image.PlaceImgUrl(); + img.Should().Be("https://placeimg.com/640/480/any"); - img = image.PlaceImgUrl(777, 222, filter: PlaceImgFilter.Grayscale); - img.Should().Be("https://placeimg.com/777/222/any/grayscale"); + img = image.PlaceImgUrl(777, 222, filter: PlaceImgFilter.Grayscale); + img.Should().Be("https://placeimg.com/777/222/any/grayscale"); - img = image.PlaceImgUrl(777, 222, PlaceImgCategory.Architecture, PlaceImgFilter.Sepia); - img.Should().Be("https://placeimg.com/777/222/arch/sepia"); + img = image.PlaceImgUrl(777, 222, PlaceImgCategory.Architecture, PlaceImgFilter.Sepia); + img.Should().Be("https://placeimg.com/777/222/arch/sepia"); - img = image.PlaceImgUrl(777, 333, PlaceImgCategory.Architecture); - img.Should().Be("https://placeimg.com/777/333/arch"); + img = image.PlaceImgUrl(777, 333, PlaceImgCategory.Architecture); + img.Should().Be("https://placeimg.com/777/333/arch"); - img = image.PlaceImgUrl(777, 444, PlaceImgCategory.Tech); - img.Should().Be("https://placeimg.com/777/444/tech"); - } + img = image.PlaceImgUrl(777, 444, PlaceImgCategory.Tech); + img.Should().Be("https://placeimg.com/777/444/tech"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/DataSetTests/InternetTests.cs b/Source/Bogus.Tests/DataSetTests/InternetTests.cs index f2dca443..48c5c8c0 100644 --- a/Source/Bogus.Tests/DataSetTests/InternetTests.cs +++ b/Source/Bogus.Tests/DataSetTests/InternetTests.cs @@ -9,186 +9,185 @@ using Xunit.Abstractions; using Z.ExtensionMethods; -namespace Bogus.Tests.DataSetTests +namespace Bogus.Tests.DataSetTests; + +public class InternetTests : SeededTest { - public class InternetTests : SeededTest + private readonly ITestOutputHelper console; + + public InternetTests(ITestOutputHelper console) { - private readonly ITestOutputHelper console; + this.console = console; + internet = new Internet(); + } - public InternetTests(ITestOutputHelper console) - { - this.console = console; - internet = new Internet(); - } + private readonly Internet internet; - private readonly Internet internet; + [Fact] + public void can_generate_a_password() + { + var pw = internet.Password(); + pw.Should().Be("YmaMy0eWbv"); - [Fact] - public void can_generate_a_password() - { - var pw = internet.Password(); - pw.Should().Be("YmaMy0eWbv"); + var pw2 = internet.Password(regexPattern: @"\W"); + pw2.Should().Be(@""">({=*`/{]"); + } - var pw2 = internet.Password(regexPattern: @"\W"); - pw2.Should().Be(@""">({=*`/{]"); - } + [Fact] + public void can_generate_an_example_email() + { + var email = internet.ExampleEmail(); - [Fact] - public void can_generate_an_example_email() - { - var email = internet.ExampleEmail(); + email.Should().EndWith("@example.com"); + email.GetBefore("@").Should().Contain("."); + } - email.Should().EndWith("@example.com"); - email.GetBefore("@").Should().Contain("."); - } + [Fact] + public void can_generate_mac_address() + { + internet.Mac().Should().Be("9a:1c:d0:a5:09:9f"); + } - [Fact] - public void can_generate_mac_address() - { - internet.Mac().Should().Be("9a:1c:d0:a5:09:9f"); - } + [Fact] + public void can_generate_mac_address_with_separator() + { + internet.Mac("_").Should().Be("9a_1c_d0_a5_09_9f"); + } - [Fact] - public void can_generate_mac_address_with_separator() - { - internet.Mac("_").Should().Be("9a_1c_d0_a5_09_9f"); - } + [Fact] + public void can_get_a_domain_name() + { + internet.DomainName().Should().Be("lee.com"); + } - [Fact] - public void can_get_a_domain_name() - { - internet.DomainName().Should().Be("lee.com"); - } + [Fact] + public void can_get_a_domain_suffix() + { + internet.DomainSuffix().Should().Be("name"); + } - [Fact] - public void can_get_a_domain_suffix() - { - internet.DomainSuffix().Should().Be("name"); - } + [Fact] + public void can_get_a_random_ip_address() + { + internet.Ip().Should().Be("154.28.208.165"); + } - [Fact] - public void can_get_a_random_ip_address() - { - internet.Ip().Should().Be("154.28.208.165"); - } + [Fact] + public void can_get_a_random_ipv6_address() + { + internet.Ipv6().Should().Be("da23:9c4c:e0c4:2dd7:e3c4:a896:17f2:55b2"); + } - [Fact] - public void can_get_a_random_ipv6_address() - { - internet.Ipv6().Should().Be("da23:9c4c:e0c4:2dd7:e3c4:a896:17f2:55b2"); - } + [Fact] + public void can_get_a_urlpath_with_a_specific_domain() + { + internet.UrlWithPath(domain: "bitarmory.com").Should().Be("https://bitarmory.com/soft/deposit"); + } - [Fact] - public void can_get_a_urlpath_with_a_specific_domain() - { - internet.UrlWithPath(domain: "bitarmory.com").Should().Be("https://bitarmory.com/soft/deposit"); - } + [Fact] + public void can_get_an_email() + { + var email = internet.Email(); - [Fact] - public void can_get_an_email() - { - var email = internet.Email(); + email.Should().Be("Bernhard.Schultz@yahoo.com"); + } - email.Should().Be("Bernhard.Schultz@yahoo.com"); - } + [Fact] + public void can_get_an_username() + { + var user = internet.UserName(); - [Fact] - public void can_get_an_username() - { - var user = internet.UserName(); + user.Should().Be("Lee_Brekke3"); + } - user.Should().Be("Lee_Brekke3"); - } + [Fact] + public void can_get_avatar() + { + var avatar = internet.Avatar(); - [Fact] - public void can_get_avatar() - { - var avatar = internet.Avatar(); + avatar.Should().Be("https://cloudflare-ipfs.com/ipfs/Qmd3W5DuhgHirLHGVixi6V76LhCkZUz6pnFt5AJBiyvHye/avatar/754.jpg"); + } - avatar.Should().Be("https://cloudflare-ipfs.com/ipfs/Qmd3W5DuhgHirLHGVixi6V76LhCkZUz6pnFt5AJBiyvHye/avatar/754.jpg"); - } + [Fact] + public void can_get_html_color() + { + internet.Color().Should().Be("#4d0e68"); + } - [Fact] - public void can_get_html_color() - { - internet.Color().Should().Be("#4d0e68"); - } + [Fact] + public void can_get_color_in_format() + { + internet.Color(format:ColorFormat.Rgb).Should().Be("rgb(77,14,104)"); + } - [Fact] - public void can_get_color_in_format() - { - internet.Color(format:ColorFormat.Rgb).Should().Be("rgb(77,14,104)"); - } + [Fact] + public void can_get_color_in_delimited_format() + { + internet.Color(format: ColorFormat.Delimited).Should().Be("77,14,104"); + } - [Fact] - public void can_get_color_in_delimited_format() - { - internet.Color(format: ColorFormat.Delimited).Should().Be("77,14,104"); - } + [Fact] + public void can_get_color_in_grayscale() + { + internet.Color(grayscale: true).Should().Be("#4d4d4d"); + } - [Fact] - public void can_get_color_in_grayscale() - { - internet.Color(grayscale: true).Should().Be("#4d4d4d"); - } + [Fact] + public void can_get_url_with_path() + { + internet.UrlWithPath().Should().Be("https://ambrose.net/soft/deposit"); + internet.UrlRootedPath(); + } - [Fact] - public void can_get_url_with_path() - { - internet.UrlWithPath().Should().Be("https://ambrose.net/soft/deposit"); - internet.UrlRootedPath(); - } + [Fact] + public void can_gets_a_domain_word() + { + internet.DomainWord().Should().Be("lee"); + } - [Fact] - public void can_gets_a_domain_word() - { - internet.DomainWord().Should().Be("lee"); - } + [Fact] + public void can_make_email_with_custom_options() + { + var email = internet.Email(provider: "x.y.z.com"); - [Fact] - public void can_make_email_with_custom_options() - { - var email = internet.Email(provider: "x.y.z.com"); + email.Should().Be("Lee_Brekke3@x.y.z.com"); - email.Should().Be("Lee_Brekke3@x.y.z.com"); + email = internet.Email("cowboy"); - email = internet.Email("cowboy"); + email.Should().Be("cowboy.Beatty30@yahoo.com"); + } - email.Should().Be("cowboy.Beatty30@yahoo.com"); - } + [Fact] + public void can_pick_random_browser() + { + var userAgents = Enumerable.Range(1, 1_000) + .Select(i => internet.UserAgent()) + .ToArray(); - [Fact] - public void can_pick_random_browser() + var req = new System.Net.Http.HttpRequestMessage(); + foreach( var userAgent in userAgents ) { - var userAgents = Enumerable.Range(1, 1_000) - .Select(i => internet.UserAgent()) - .ToArray(); - - var req = new System.Net.Http.HttpRequestMessage(); - foreach( var userAgent in userAgents ) - { - Action act = () => req.Headers.Add("User-Agent", userAgent); - act.Should().NotThrow(); - } + Action act = () => req.Headers.Add("User-Agent", userAgent); + act.Should().NotThrow(); } + } - [Theory] - [InlineData("Анна", "Фомина", "Анна11", 1337)] - [InlineData("Анна", "Фомина", "Анна_Фомина13", 228)] - [InlineData("Анна", "Фомина", "Анна.Фомина", 302)] - public void can_get_username_with_unicode_characters(string first, string last, string expected, int seed) - { - internet.Random = new Randomizer(seed); - internet.UserNameUnicode(first, last).Should().Be(expected); - } + [Theory] + [InlineData("Анна", "Фомина", "Анна11", 1337)] + [InlineData("Анна", "Фомина", "Анна_Фомина13", 228)] + [InlineData("Анна", "Фомина", "Анна.Фомина", 302)] + public void can_get_username_with_unicode_characters(string first, string last, string expected, int seed) + { + internet.Random = new Randomizer(seed); + internet.UserNameUnicode(first, last).Should().Be(expected); + } - [Fact] - public void can_generate_random_port_number() - { - internet.Port().Should() - .BeGreaterOrEqualTo(IPEndPoint.MinPort + 1) - .And - .BeLessOrEqualTo(IPEndPoint.MaxPort); - } + [Fact] + public void can_generate_random_port_number() + { + internet.Port().Should() + .BeGreaterOrEqualTo(IPEndPoint.MinPort + 1) + .And + .BeLessOrEqualTo(IPEndPoint.MaxPort); } } diff --git a/Source/Bogus.Tests/DataSetTests/LoremTests.cs b/Source/Bogus.Tests/DataSetTests/LoremTests.cs index eb7a992b..abc7f350 100644 --- a/Source/Bogus.Tests/DataSetTests/LoremTests.cs +++ b/Source/Bogus.Tests/DataSetTests/LoremTests.cs @@ -5,160 +5,159 @@ using Xunit.Abstractions; using Z.ExtensionMethods; -namespace Bogus.Tests.DataSetTests +namespace Bogus.Tests.DataSetTests; + +public class LoremTests : SeededTest { - public class LoremTests : SeededTest - { - private readonly ITestOutputHelper console; - - public LoremTests(ITestOutputHelper console) - { - this.console = console; - lorem = new Lorem(); - } - - private readonly Lorem lorem; - - [Fact] - public void can_get_3_words() - { - var test = lorem.Words(); - - test.Dump(); - - test.Should() - .HaveCount(3); - - test.Should().Equal("id", "aut", "vel"); - - //test.ForEach(w => w.Should().NotBeNullOrWhiteSpace()); - } - - [Fact] - public void can_get_5_words() - { - var test = lorem.Words(5); - - test.Dump(); - - test.Should() - .HaveCount(5); - - test.Should().Equal("id", - "aut", - "vel", - "facilis", - "aperiam"); - - //test.ForEach(w => w.Should().NotBeNullOrWhiteSpace()); - } - - [Fact] - public void can_get_a_paragraph() - { - lorem.Paragraph() - .Split(". ").Length.Should().Be(5); // para of 5 sentences. - } - - [Fact] - public void paragraph_with_zero_sentences() - { - var text = lorem.Paragraph(0); - - text.Count(c => c == '.') - .Should() - .BeGreaterOrEqualTo(0) - .And - .BeLessOrEqualTo(3); - } - - [Fact] - public void can_get_a_random_word() - { - lorem.Word().Should().Be("id"); - lorem.Word().Should().Be("aut"); - lorem.Word().Should().Be("vel"); - } - - [Fact] - public void can_get_a_sentence() - { - lorem.Sentence().Split(' ').Length.Should().BeGreaterThan(3); - } - - [Fact] - public void can_get_a_sentence_with_options() - { - lorem.Sentence(5).Split(' ').Length.Should().Be(5); - } - - [Fact] - public void can_get_a_sentences_with_range_option() - { - lorem.Sentence(10, 5).Split(' ').Length.Should().Be(13); - } - - [Fact] - public void can_get_paragraphs() - { - lorem.Paragraphs() - .Split("\n\n").Length.Should().Be(3); - } - - [Fact] - public void can_get_random_number_of_paragraphs() - { - var text = lorem.Paragraphs(5, 7); - - console.Dump(text); - - text.Split("\n\n") - .Length.Should() - .BeGreaterOrEqualTo(5) - .And - .BeLessOrEqualTo(7); - } - - [Fact] - public void check_separator_works() - { - var text = lorem.Paragraphs(5, 7, "
"); - - text.Split("
").Length - .Should() - .BeGreaterOrEqualTo(5) - .And - .BeLessOrEqualTo(7); - } - - [Fact] - public void can_get_some_letters() - { - var c = lorem.Letter(); - c.Should().Be("i"); - - - var chars = lorem.Letter(100); - chars.Length.Should().Be(100); - chars.Should().Be("eiblrueeulrtiorismecntonniaeaaumrumclrquoqaeoiehdtueuteisquagsieuiuturutunuuaiuamisseqvnqeratepilptt"); - } - - [Fact] - public void can_get_some_lorem_lines() - { - lorem.Lines().Split(" ").Length.Should().BeGreaterThan(5); - } - - [Fact] - public void can_get_some_lorem_text() - { - lorem.Text().Split(" ").Length.Should().BeGreaterThan(5); - } - - [Fact] - public void can_slugify_lorem() - { - lorem.Slug(5).Should().Be("id-aut-vel-facilis-aperiam"); - } + private readonly ITestOutputHelper console; + + public LoremTests(ITestOutputHelper console) + { + this.console = console; + lorem = new Lorem(); + } + + private readonly Lorem lorem; + + [Fact] + public void can_get_3_words() + { + var test = lorem.Words(); + + test.Dump(); + + test.Should() + .HaveCount(3); + + test.Should().Equal("id", "aut", "vel"); + + //test.ForEach(w => w.Should().NotBeNullOrWhiteSpace()); + } + + [Fact] + public void can_get_5_words() + { + var test = lorem.Words(5); + + test.Dump(); + + test.Should() + .HaveCount(5); + + test.Should().Equal("id", + "aut", + "vel", + "facilis", + "aperiam"); + + //test.ForEach(w => w.Should().NotBeNullOrWhiteSpace()); + } + + [Fact] + public void can_get_a_paragraph() + { + lorem.Paragraph() + .Split(". ").Length.Should().Be(5); // para of 5 sentences. + } + + [Fact] + public void paragraph_with_zero_sentences() + { + var text = lorem.Paragraph(0); + + text.Count(c => c == '.') + .Should() + .BeGreaterOrEqualTo(0) + .And + .BeLessOrEqualTo(3); + } + + [Fact] + public void can_get_a_random_word() + { + lorem.Word().Should().Be("id"); + lorem.Word().Should().Be("aut"); + lorem.Word().Should().Be("vel"); + } + + [Fact] + public void can_get_a_sentence() + { + lorem.Sentence().Split(' ').Length.Should().BeGreaterThan(3); + } + + [Fact] + public void can_get_a_sentence_with_options() + { + lorem.Sentence(5).Split(' ').Length.Should().Be(5); + } + + [Fact] + public void can_get_a_sentences_with_range_option() + { + lorem.Sentence(10, 5).Split(' ').Length.Should().Be(13); + } + + [Fact] + public void can_get_paragraphs() + { + lorem.Paragraphs() + .Split("\n\n").Length.Should().Be(3); + } + + [Fact] + public void can_get_random_number_of_paragraphs() + { + var text = lorem.Paragraphs(5, 7); + + console.Dump(text); + + text.Split("\n\n") + .Length.Should() + .BeGreaterOrEqualTo(5) + .And + .BeLessOrEqualTo(7); + } + + [Fact] + public void check_separator_works() + { + var text = lorem.Paragraphs(5, 7, "
"); + + text.Split("
").Length + .Should() + .BeGreaterOrEqualTo(5) + .And + .BeLessOrEqualTo(7); + } + + [Fact] + public void can_get_some_letters() + { + var c = lorem.Letter(); + c.Should().Be("i"); + + + var chars = lorem.Letter(100); + chars.Length.Should().Be(100); + chars.Should().Be("eiblrueeulrtiorismecntonniaeaaumrumclrquoqaeoiehdtueuteisquagsieuiuturutunuuaiuamisseqvnqeratepilptt"); + } + + [Fact] + public void can_get_some_lorem_lines() + { + lorem.Lines().Split(" ").Length.Should().BeGreaterThan(5); + } + + [Fact] + public void can_get_some_lorem_text() + { + lorem.Text().Split(" ").Length.Should().BeGreaterThan(5); + } + + [Fact] + public void can_slugify_lorem() + { + lorem.Slug(5).Should().Be("id-aut-vel-facilis-aperiam"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/DataSetTests/MusicTests.cs b/Source/Bogus.Tests/DataSetTests/MusicTests.cs index 86e8260c..d22e2059 100644 --- a/Source/Bogus.Tests/DataSetTests/MusicTests.cs +++ b/Source/Bogus.Tests/DataSetTests/MusicTests.cs @@ -3,23 +3,22 @@ using Xunit; using Xunit.Abstractions; -namespace Bogus.Tests.DataSetTests -{ - public class MusicTests : SeededTest - { - private readonly ITestOutputHelper console; - private Music music; +namespace Bogus.Tests.DataSetTests; - public MusicTests(ITestOutputHelper console) - { - this.console = console; - this.music = new Music(); - } +public class MusicTests : SeededTest +{ + private readonly ITestOutputHelper console; + private Music music; - [Fact] - public void can_generate_genre() - { - this.music.Genre().Should().Be("Hip Hop"); - } + public MusicTests(ITestOutputHelper console) + { + this.console = console; + this.music = new Music(); } + + [Fact] + public void can_generate_genre() + { + this.music.Genre().Should().Be("Hip Hop"); + } } \ No newline at end of file diff --git a/Source/Bogus.Tests/DataSetTests/NameTests.cs b/Source/Bogus.Tests/DataSetTests/NameTests.cs index a6320f3c..25d7aff0 100644 --- a/Source/Bogus.Tests/DataSetTests/NameTests.cs +++ b/Source/Bogus.Tests/DataSetTests/NameTests.cs @@ -2,176 +2,175 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.DataSetTests +namespace Bogus.Tests.DataSetTests; + +public class NameTests : SeededTest { - public class NameTests : SeededTest - { - public NameTests() - { - name = new Name(); - } - - private readonly Name name; - - [Fact] - public void can_get_first_name() - { - name.FirstName().Should().Be("Lee"); - } - - [Fact] - public void can_get_female_first_name() - { - name.FirstName(Name.Gender.Female).Should().Be("Lindsay"); - } - - [Fact] - public void can_get_male_first_name() - { - name.FirstName(Name.Gender.Male).Should().Be("Stuart"); - } - - [Fact] - public void can_get_first_name_when_locale_dataset_is_split_in_male_female() - { - var n = new Name("ru"); - - n.FirstName().Should().Be("Анастасия"); - } - - [Fact] - public void can_get_last_name() - { - name.LastName().Should().Be("Mitchell"); - } - - [Fact] - public void can_get_last_name_when_locale_dataset_is_split_in_male_female() - { - var n = new Name("ru"); - - n.LastName().Should().Be("Киселева"); - } - - [Fact] - public void can_get_prefix() - { - name.Prefix().Should().Be("Mr."); - } - - [Fact] - public void can_get_suffix() - { - name.Suffix().Should().Be("V"); - } - - [Fact] - public void should_be_able_to_get_any_full_name() - { - var n = name.FindName(); - n.Length.Should().BeGreaterThan(4); - n.Should().Contain(" "); - } - - [Fact] - public void should_be_able_to_get_any_name_with_options() - { - name.FindName("cowboy") - .Should().StartWith("cowboy"); - - name.FindName(lastName: "cowboy") - .Should().EndWith("cowboy"); - - name.FindName(withPrefix: false, withSuffix: false) - .Should().Contain(" "); - - name.FindName("cowboy", withPrefix: false, withSuffix: false) - .Should().StartWith("cowboy"); - - name.FindName(lastName: "cowboy", withPrefix: false, withSuffix: false) - .Should().EndWith("cowboy"); - } - - [Fact] - public void should_be_able_to_get_job_area() - { - name.JobArea().Should().Be("Communications"); - } - - [Fact] - public void should_be_able_to_get_job_description() - { - name.JobDescriptor().Should().Be("Investor"); - } - - [Fact] - public void should_be_able_to_get_job_title() - { - name.JobTitle().Should().Be("Investor Research Assistant"); - } - - [Fact] - public void should_be_able_to_get_job_type() - { - name.JobType().Should().Be("Orchestrator"); - } - - [Fact] - public void should_be_able_to_get_locale_full_name() - { - var n = new Name("ru"); - n.FindName().Should().Be("Анастасия Евсеева"); - } - - [Fact] - public void switch_locale_syntax() - { - var n = new Name("ru"); - n.LastName().Should().Be("Киселева"); - - //switch to EN - n["en"].LastName().Should().Be("Schultz"); - } - - [Fact] - public void can_get_a_full_name() - { - name.FullName().Should().Be("Lee Brekke"); - } - - [Fact] - public void full_name_component_genders_should_match() - { - var n = new Name("ru") - { - Random = new Randomizer(31337) - }; - n.FullName().Should().Be("Людмила Тетерина"); - } - - [Fact] - public void locales_with_empty_array_suffix_should_be_null() - { - var n = new Name("ru"); - n.Prefix().Should().BeNullOrEmpty(); - n.Suffix().Should().BeNullOrEmpty(); - - n = new Name("it"); - n.Suffix().Should().BeNullOrEmpty(); - } - - [Fact] - public void locales_that_dont_support_gender_first_names_should_return_generic() - { - - var n = new Name("ge") { Random = new Randomizer(31337) }; - n.FirstName(Name.Gender.Female).Should().Be("ხირხელა"); - - n = new Name("ge") { Random = new Randomizer(31337) }; - n.FirstName(Name.Gender.Male).Should().Be("ხირხელა"); - - n = new Name("ge") { Random = new Randomizer(31337) }; - n.FirstName().Should().Be("ხირხელა"); - } + public NameTests() + { + name = new Name(); + } + + private readonly Name name; + + [Fact] + public void can_get_first_name() + { + name.FirstName().Should().Be("Lee"); + } + + [Fact] + public void can_get_female_first_name() + { + name.FirstName(Name.Gender.Female).Should().Be("Lindsay"); + } + + [Fact] + public void can_get_male_first_name() + { + name.FirstName(Name.Gender.Male).Should().Be("Stuart"); + } + + [Fact] + public void can_get_first_name_when_locale_dataset_is_split_in_male_female() + { + var n = new Name("ru"); + + n.FirstName().Should().Be("Анастасия"); + } + + [Fact] + public void can_get_last_name() + { + name.LastName().Should().Be("Mitchell"); + } + + [Fact] + public void can_get_last_name_when_locale_dataset_is_split_in_male_female() + { + var n = new Name("ru"); + + n.LastName().Should().Be("Киселева"); + } + + [Fact] + public void can_get_prefix() + { + name.Prefix().Should().Be("Mr."); + } + + [Fact] + public void can_get_suffix() + { + name.Suffix().Should().Be("V"); + } + + [Fact] + public void should_be_able_to_get_any_full_name() + { + var n = name.FindName(); + n.Length.Should().BeGreaterThan(4); + n.Should().Contain(" "); + } + + [Fact] + public void should_be_able_to_get_any_name_with_options() + { + name.FindName("cowboy") + .Should().StartWith("cowboy"); + + name.FindName(lastName: "cowboy") + .Should().EndWith("cowboy"); + + name.FindName(withPrefix: false, withSuffix: false) + .Should().Contain(" "); + + name.FindName("cowboy", withPrefix: false, withSuffix: false) + .Should().StartWith("cowboy"); + + name.FindName(lastName: "cowboy", withPrefix: false, withSuffix: false) + .Should().EndWith("cowboy"); + } + + [Fact] + public void should_be_able_to_get_job_area() + { + name.JobArea().Should().Be("Communications"); + } + + [Fact] + public void should_be_able_to_get_job_description() + { + name.JobDescriptor().Should().Be("Investor"); + } + + [Fact] + public void should_be_able_to_get_job_title() + { + name.JobTitle().Should().Be("Investor Research Assistant"); + } + + [Fact] + public void should_be_able_to_get_job_type() + { + name.JobType().Should().Be("Orchestrator"); + } + + [Fact] + public void should_be_able_to_get_locale_full_name() + { + var n = new Name("ru"); + n.FindName().Should().Be("Анастасия Евсеева"); + } + + [Fact] + public void switch_locale_syntax() + { + var n = new Name("ru"); + n.LastName().Should().Be("Киселева"); + + //switch to EN + n["en"].LastName().Should().Be("Schultz"); + } + + [Fact] + public void can_get_a_full_name() + { + name.FullName().Should().Be("Lee Brekke"); + } + + [Fact] + public void full_name_component_genders_should_match() + { + var n = new Name("ru") + { + Random = new Randomizer(31337) + }; + n.FullName().Should().Be("Людмила Тетерина"); + } + + [Fact] + public void locales_with_empty_array_suffix_should_be_null() + { + var n = new Name("ru"); + n.Prefix().Should().BeNullOrEmpty(); + n.Suffix().Should().BeNullOrEmpty(); + + n = new Name("it"); + n.Suffix().Should().BeNullOrEmpty(); + } + + [Fact] + public void locales_that_dont_support_gender_first_names_should_return_generic() + { + + var n = new Name("ge") { Random = new Randomizer(31337) }; + n.FirstName(Name.Gender.Female).Should().Be("ხირხელა"); + + n = new Name("ge") { Random = new Randomizer(31337) }; + n.FirstName(Name.Gender.Male).Should().Be("ხირხელა"); + + n = new Name("ge") { Random = new Randomizer(31337) }; + n.FirstName().Should().Be("ხირხელა"); } } diff --git a/Source/Bogus.Tests/DataSetTests/PhoneNumbersTest.cs b/Source/Bogus.Tests/DataSetTests/PhoneNumbersTest.cs index fbcff4ba..c2dbbd1a 100644 --- a/Source/Bogus.Tests/DataSetTests/PhoneNumbersTest.cs +++ b/Source/Bogus.Tests/DataSetTests/PhoneNumbersTest.cs @@ -2,36 +2,35 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.DataSetTests +namespace Bogus.Tests.DataSetTests; + +public class PhoneNumbersTest : SeededTest { - public class PhoneNumbersTest : SeededTest + public PhoneNumbersTest() { - public PhoneNumbersTest() - { - phone = new PhoneNumbers(); - } + phone = new PhoneNumbers(); + } - private readonly PhoneNumbers phone; + private readonly PhoneNumbers phone; - [Fact] - public void can_get_phone_number() - { - phone.PhoneNumber() - .Should().Be("260-860-6439 x1750"); - } + [Fact] + public void can_get_phone_number() + { + phone.PhoneNumber() + .Should().Be("260-860-6439 x1750"); + } - [Fact] - public void can_get_phone_number_of_specific_format() - { - phone.PhoneNumber("## ### ####") - .Should().Be("61 860 6064"); - } + [Fact] + public void can_get_phone_number_of_specific_format() + { + phone.PhoneNumber("## ### ####") + .Should().Be("61 860 6064"); + } - [Fact] - public void can_get_phone_number_via_formats_index() - { - phone.PhoneNumberFormat(1) - .Should().Be("(686) 206-0643"); - } + [Fact] + public void can_get_phone_number_via_formats_index() + { + phone.PhoneNumberFormat(1) + .Should().Be("(686) 206-0643"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/DataSetTests/RantTests.cs b/Source/Bogus.Tests/DataSetTests/RantTests.cs index 8ce775a6..8c1c493b 100644 --- a/Source/Bogus.Tests/DataSetTests/RantTests.cs +++ b/Source/Bogus.Tests/DataSetTests/RantTests.cs @@ -1,36 +1,35 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.DataSetTests +namespace Bogus.Tests.DataSetTests; + +public class RantTests : SeededTest { - public class RantTests : SeededTest + public RantTests() { - public RantTests() - { - rant = new DataSets.Rant(); - } + rant = new DataSets.Rant(); + } - private readonly DataSets.Rant rant; + private readonly DataSets.Rant rant; - [Fact] - public void can_get_an_array_of_reviews() - { - var reviews = rant.Reviews("foobar", 3); + [Fact] + public void can_get_an_array_of_reviews() + { + var reviews = rant.Reviews("foobar", 3); - var truth = new[] - { - "one of my hobbies is poetry. and when i'm writing poems this works great.", - "I tried to annihilate it but got bonbon all over it.", - "My co-worker Merwin has one of these. He says it looks bubbly." - }; - //reviews.Length.Should().Be(3); - reviews.Should().BeEquivalentTo(truth); - } + var truth = new[] + { + "one of my hobbies is poetry. and when i'm writing poems this works great.", + "I tried to annihilate it but got bonbon all over it.", + "My co-worker Merwin has one of these. He says it looks bubbly." + }; + //reviews.Length.Should().Be(3); + reviews.Should().BeEquivalentTo(truth); + } - [Fact] - public void can_get_random_product_review() - { - rant.Review("foobar").Should().Be("one of my hobbies is poetry. and when i'm writing poems this works great."); - } + [Fact] + public void can_get_random_product_review() + { + rant.Review("foobar").Should().Be("one of my hobbies is poetry. and when i'm writing poems this works great."); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/DataSetTests/SystemTest.cs b/Source/Bogus.Tests/DataSetTests/SystemTest.cs index 1359883c..98e9f94b 100644 --- a/Source/Bogus.Tests/DataSetTests/SystemTest.cs +++ b/Source/Bogus.Tests/DataSetTests/SystemTest.cs @@ -5,151 +5,150 @@ using Z.ExtensionMethods; using Z.ExtensionMethods.ObjectExtensions; -namespace Bogus.Tests.DataSetTests +namespace Bogus.Tests.DataSetTests; + +public class SystemTest : SeededTest { - public class SystemTest : SeededTest - { - public SystemTest() - { - system = new DataSets.System(); - } - - private readonly DataSets.System system; - - [Fact] - public void can_generate_random_semver() - { - var numbers = system.Semver().Split('.'); - - numbers.TrueForAll(x => x.ToInt32() >= 0 && x.ToInt32() <= 9) - .Should().BeTrue(); - } - - [Fact] - public void can_get_a_few_common_file_exts() - { - system.CommonFileExt().Should().Be("gif"); - system.CommonFileExt().Should().Be("m1v"); - system.CommonFileExt().Should().Be("pdf"); - } - - [Fact] - public void can_get_a_random_exception() - { - var exe = system.Exception(); - - exe.Dump(); - - var exe2 = system.Exception(); - - exe2.Dump(); - } - - [Fact] - public void can_get_a_random_extension_of_an_unknown_mimetype() - { - system.FileExt("aaa/bbb").Should().Be("pfb"); - system.FileExt("aaa/bbb").Should().Be("eps"); - system.FileExt("aaa/bbb").Should().Be("cmx"); - } - - [Fact] - public void can_get_a_random_system_version() - { - var ver = system.Version(); - - var numbers = ver.ToString().Split('.'); - - numbers.TrueForAll(x => x.ToInt32() >= 0 && x.ToInt32() <= 9) - .Should().BeTrue(); - } - - [Fact] - public void can_get_random_file_type() - { - system.FileType().Should().Be("multipart"); - system.FileType().Should().Be("audio"); - system.FileType().Should().Be("video"); - } - - [Fact] - public void can_get_some_random_mime_types() - { - system.MimeType().Should().Be("application/vnd.uoml+xml"); - system.MimeType().Should().Be("application/nss"); - system.MimeType().Should().Be("audio/x-aiff"); - } - - [Fact] - public void can_get_some_common_file_types() - { - system.CommonFileType().Should().Be("text"); - system.CommonFileType().Should().Be("video"); - system.CommonFileType().Should().Be("application"); - } - - [Fact] - public void can_get_some_common_random_file_names() - { - system.CommonFileName().Should().Be("soft_deposit.gif"); - system.CommonFileName().Should().Be("bedfordshire_directives_pixel.pdf"); - system.CommonFileName().Should().Be("lead_transmitting_methodology.gif"); - } - - [Fact] - public void can_get_some_random_extensions() - { - system.FileExt("image/jpeg").Should().Be("jpg"); - system.FileExt("image/jpeg").Should().Be("jpeg"); - system.FileExt("image/jpeg").Should().Be("jpe"); - system.FileExt("image/jpeg").Should().Be("jpg"); - } - - [Fact] - public void can_get_some_random_file_names() - { - system.FileName().Should().Be("soft_deposit.prc"); - system.FileName().Should().Be("liberian_dollar.xpr"); - system.FileName().Should().Be("handmade_rubber_computer_handcrafted_frozen_chair_transmitting.kwd"); - } - - [Fact] - public void merge_test() - { - system.GetArray("mimeTypes").OfType() - .Select(o => o["mime"].StringValue.Substring(0, o["mime"].StringValue.IndexOf('/'))) - .Distinct() - .ToArray().Dump(); - } - - [Fact] - public void can_get_directory_path_unix() - { - system.DirectoryPath().Should().Be(@"/sys"); - } - - [Fact] - public void can_get_file_path_unix() - { - system.FilePath().Should().Be("/sys/bluetooth.js"); - } - - [Fact] - public void can_get_an_android_id() - { - system.AndroidId().Should().Be("APA91D6QF2E3IvkYaKB52JW1SSkDC5IZpfBzfk6IPaXZfFrXVNTuiA3r6cj6jweAnGGuVMKTEVjTNYPcrpKQeeIRa9s20_qkYoDA-Y1830SoibG9q6IVOqm8-RjLkISEw_XqmfeunBMcolz-wjEWkwyz1vC8GjQoaeTjhhQaUeycF8MGilg13Xk"); - } - - [Fact] - public void can_get_an_apple_push_token() - { - system.ApplePushToken().Should().Be("91da090b74f2b910be0dd5991af6398351ac2ef3a6eecd74806134147385aa7e"); - } - - [Fact] - public void can_get_a_black_berry_pin() - { - system.BlackBerryPin().Should().Be("91da090b"); - } + public SystemTest() + { + system = new DataSets.System(); + } + + private readonly DataSets.System system; + + [Fact] + public void can_generate_random_semver() + { + var numbers = system.Semver().Split('.'); + + numbers.TrueForAll(x => x.ToInt32() >= 0 && x.ToInt32() <= 9) + .Should().BeTrue(); + } + + [Fact] + public void can_get_a_few_common_file_exts() + { + system.CommonFileExt().Should().Be("gif"); + system.CommonFileExt().Should().Be("m1v"); + system.CommonFileExt().Should().Be("pdf"); + } + + [Fact] + public void can_get_a_random_exception() + { + var exe = system.Exception(); + + exe.Dump(); + + var exe2 = system.Exception(); + + exe2.Dump(); + } + + [Fact] + public void can_get_a_random_extension_of_an_unknown_mimetype() + { + system.FileExt("aaa/bbb").Should().Be("pfb"); + system.FileExt("aaa/bbb").Should().Be("eps"); + system.FileExt("aaa/bbb").Should().Be("cmx"); + } + + [Fact] + public void can_get_a_random_system_version() + { + var ver = system.Version(); + + var numbers = ver.ToString().Split('.'); + + numbers.TrueForAll(x => x.ToInt32() >= 0 && x.ToInt32() <= 9) + .Should().BeTrue(); + } + + [Fact] + public void can_get_random_file_type() + { + system.FileType().Should().Be("multipart"); + system.FileType().Should().Be("audio"); + system.FileType().Should().Be("video"); + } + + [Fact] + public void can_get_some_random_mime_types() + { + system.MimeType().Should().Be("application/vnd.uoml+xml"); + system.MimeType().Should().Be("application/nss"); + system.MimeType().Should().Be("audio/x-aiff"); + } + + [Fact] + public void can_get_some_common_file_types() + { + system.CommonFileType().Should().Be("text"); + system.CommonFileType().Should().Be("video"); + system.CommonFileType().Should().Be("application"); + } + + [Fact] + public void can_get_some_common_random_file_names() + { + system.CommonFileName().Should().Be("soft_deposit.gif"); + system.CommonFileName().Should().Be("bedfordshire_directives_pixel.pdf"); + system.CommonFileName().Should().Be("lead_transmitting_methodology.gif"); + } + + [Fact] + public void can_get_some_random_extensions() + { + system.FileExt("image/jpeg").Should().Be("jpg"); + system.FileExt("image/jpeg").Should().Be("jpeg"); + system.FileExt("image/jpeg").Should().Be("jpe"); + system.FileExt("image/jpeg").Should().Be("jpg"); + } + + [Fact] + public void can_get_some_random_file_names() + { + system.FileName().Should().Be("soft_deposit.prc"); + system.FileName().Should().Be("liberian_dollar.xpr"); + system.FileName().Should().Be("handmade_rubber_computer_handcrafted_frozen_chair_transmitting.kwd"); + } + + [Fact] + public void merge_test() + { + system.GetArray("mimeTypes").OfType() + .Select(o => o["mime"].StringValue.Substring(0, o["mime"].StringValue.IndexOf('/'))) + .Distinct() + .ToArray().Dump(); + } + + [Fact] + public void can_get_directory_path_unix() + { + system.DirectoryPath().Should().Be(@"/sys"); + } + + [Fact] + public void can_get_file_path_unix() + { + system.FilePath().Should().Be("/sys/bluetooth.js"); + } + + [Fact] + public void can_get_an_android_id() + { + system.AndroidId().Should().Be("APA91D6QF2E3IvkYaKB52JW1SSkDC5IZpfBzfk6IPaXZfFrXVNTuiA3r6cj6jweAnGGuVMKTEVjTNYPcrpKQeeIRa9s20_qkYoDA-Y1830SoibG9q6IVOqm8-RjLkISEw_XqmfeunBMcolz-wjEWkwyz1vC8GjQoaeTjhhQaUeycF8MGilg13Xk"); + } + + [Fact] + public void can_get_an_apple_push_token() + { + system.ApplePushToken().Should().Be("91da090b74f2b910be0dd5991af6398351ac2ef3a6eecd74806134147385aa7e"); + } + + [Fact] + public void can_get_a_black_berry_pin() + { + system.BlackBerryPin().Should().Be("91da090b"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/DataSetTests/VehicleTest.cs b/Source/Bogus.Tests/DataSetTests/VehicleTest.cs index 2325214f..bfcba615 100644 --- a/Source/Bogus.Tests/DataSetTests/VehicleTest.cs +++ b/Source/Bogus.Tests/DataSetTests/VehicleTest.cs @@ -2,45 +2,44 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.DataSetTests +namespace Bogus.Tests.DataSetTests; + +public class VehicleTest : SeededTest { - public class VehicleTest : SeededTest + private Vehicle vehicle; + + public VehicleTest() + { + vehicle = new Vehicle(); + } + + [Fact] + public void can_get_a_vin_number() + { + vehicle.Vin().Should().Be("L3TN1M1OHAY675714"); + } + + [Fact] + public void can_get_a_manufacture() + { + vehicle.Manufacturer().Should().Be("Maserati"); + } + + [Fact] + public void can_get_a_model() + { + vehicle.Model().Should().Be("Prius"); + } + + [Fact] + public void can_get_a_type() + { + vehicle.Type().Should().Be("Minivan"); + } + + [Fact] + public void can_get_a_fuel() { - private Vehicle vehicle; - - public VehicleTest() - { - vehicle = new Vehicle(); - } - - [Fact] - public void can_get_a_vin_number() - { - vehicle.Vin().Should().Be("L3TN1M1OHAY675714"); - } - - [Fact] - public void can_get_a_manufacture() - { - vehicle.Manufacturer().Should().Be("Maserati"); - } - - [Fact] - public void can_get_a_model() - { - vehicle.Model().Should().Be("Prius"); - } - - [Fact] - public void can_get_a_type() - { - vehicle.Type().Should().Be("Minivan"); - } - - [Fact] - public void can_get_a_fuel() - { - vehicle.Fuel().Should().Be("Gasoline"); - } + vehicle.Fuel().Should().Be("Gasoline"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/DistributionTests/GaussianTests.cs b/Source/Bogus.Tests/DistributionTests/GaussianTests.cs index a64378c5..8a19516c 100644 --- a/Source/Bogus.Tests/DistributionTests/GaussianTests.cs +++ b/Source/Bogus.Tests/DistributionTests/GaussianTests.cs @@ -4,203 +4,202 @@ using Xunit; using Xunit.Abstractions; -namespace Bogus.Tests.DistributionTests +namespace Bogus.Tests.DistributionTests; + +public class GaussianTests : SeededTest { - public class GaussianTests : SeededTest + + private readonly ITestOutputHelper console; + private Randomizer r; + + public GaussianTests(ITestOutputHelper console) { + this.console = console; + r = new Randomizer(); + } - private readonly ITestOutputHelper console; - private Randomizer r; + /// + /// Given a reasonable number of generated random numbers using the Gaussian methods, the mean and + /// standard deviation of those generated numbers should be very close the mean and standard deviation + /// that was specified when generating those numbers. + /// + /// + /// Because we can't expect the mean and standard deviation to match exactly, we allow a 10% tolerance. + /// + [Fact] + public void generated_doubles_should_match_specified_parameters() + { + double desiredMean = 105.5d; + double desiredStandardDeviation = 11.2d; + int desiredSampleSize = 1000; + double sum = 0d; + double[] dataPoints = new Double[desiredSampleSize]; - public GaussianTests(ITestOutputHelper console) + for (int i = 0; i < desiredSampleSize; i++) { - this.console = console; - r = new Randomizer(); + double value = r.GaussianDouble(desiredMean, desiredStandardDeviation); + sum += value; + dataPoints[i] = value; } - /// - /// Given a reasonable number of generated random numbers using the Gaussian methods, the mean and - /// standard deviation of those generated numbers should be very close the mean and standard deviation - /// that was specified when generating those numbers. - /// - /// - /// Because we can't expect the mean and standard deviation to match exactly, we allow a 10% tolerance. - /// - [Fact] - public void generated_doubles_should_match_specified_parameters() + double mean = sum / desiredSampleSize; + console.WriteLine($"Desired Mean: {desiredMean}; Actual Mean: {mean}"); + + // Must be within tolerance of 10% + mean.Should().BeInRange(desiredMean * 0.9, desiredMean * 1.1); + + // Calculate the Standard Deviation, now that we have the mean + double sumSquares = 0; + for (int i = 0; i < desiredSampleSize; i++) { - double desiredMean = 105.5d; - double desiredStandardDeviation = 11.2d; - int desiredSampleSize = 1000; - double sum = 0d; - double[] dataPoints = new Double[desiredSampleSize]; - - for (int i = 0; i < desiredSampleSize; i++) - { - double value = r.GaussianDouble(desiredMean, desiredStandardDeviation); - sum += value; - dataPoints[i] = value; - } - - double mean = sum / desiredSampleSize; - console.WriteLine($"Desired Mean: {desiredMean}; Actual Mean: {mean}"); - - // Must be within tolerance of 10% - mean.Should().BeInRange(desiredMean * 0.9, desiredMean * 1.1); - - // Calculate the Standard Deviation, now that we have the mean - double sumSquares = 0; - for (int i = 0; i < desiredSampleSize; i++) - { - sumSquares += (dataPoints[i] - mean) * (dataPoints[i] - mean); - } - - double standardDeviation = Math.Sqrt(sumSquares / desiredSampleSize); - console.WriteLine( - $"Desired Standard Deviation: {desiredStandardDeviation}; Actual Standard Deviation {standardDeviation}"); - - // Must be withing a tolerance of 10% - standardDeviation.Should().BeInRange(desiredStandardDeviation * 0.9, desiredStandardDeviation * 1.1); + sumSquares += (dataPoints[i] - mean) * (dataPoints[i] - mean); } + double standardDeviation = Math.Sqrt(sumSquares / desiredSampleSize); + console.WriteLine( + $"Desired Standard Deviation: {desiredStandardDeviation}; Actual Standard Deviation {standardDeviation}"); + + // Must be withing a tolerance of 10% + standardDeviation.Should().BeInRange(desiredStandardDeviation * 0.9, desiredStandardDeviation * 1.1); + } + - /// - /// Given a reasonable number of generated random numbers using the Gaussian methods, the mean and - /// standard deviation of those generated numbers should be very close the mean and standard deviation - /// that was specified when generating those numbers. - /// - /// - /// Because we can't expect the mean and standard deviation to match exactly, we allow a 10% tolerance. - /// - [Fact] - public void generated_decimals_should_match_specified_parameters() + /// + /// Given a reasonable number of generated random numbers using the Gaussian methods, the mean and + /// standard deviation of those generated numbers should be very close the mean and standard deviation + /// that was specified when generating those numbers. + /// + /// + /// Because we can't expect the mean and standard deviation to match exactly, we allow a 10% tolerance. + /// + [Fact] + public void generated_decimals_should_match_specified_parameters() + { + double desiredMean = 105.5d; + double desiredStandardDeviation = 11.2d; + int desiredSampleSize = 1000; + decimal sum = 0M; + decimal[] dataPoints = new decimal[desiredSampleSize]; + + for (int i = 0; i < desiredSampleSize; i++) { - double desiredMean = 105.5d; - double desiredStandardDeviation = 11.2d; - int desiredSampleSize = 1000; - decimal sum = 0M; - decimal[] dataPoints = new decimal[desiredSampleSize]; - - for (int i = 0; i < desiredSampleSize; i++) - { - decimal value = r.GaussianDecimal(desiredMean, desiredStandardDeviation); - sum += value; - dataPoints[i] = value; - } - - double mean = (double) (sum / desiredSampleSize); - console.WriteLine($"Desired Mean: {desiredMean}; Actual Mean: {mean}"); - - // Must be within tolerance of 10% - mean.Should().BeInRange(desiredMean * 0.9d, desiredMean * 1.1d); - - // Calculate the Standard Deviation, now that we have the mean - double sumSquares = 0; - for (int i = 0; i < desiredSampleSize; i++) - { - sumSquares += ((double) dataPoints[i] - mean) * ((double) dataPoints[i] - mean); - } - - double standardDeviation = Math.Sqrt(sumSquares / desiredSampleSize); - console.WriteLine( - $"Desired Standard Deviation: {desiredStandardDeviation}; Actual Standard Deviation {standardDeviation}"); - - // Must be withing a tolerance of 10% - standardDeviation.Should().BeInRange(desiredStandardDeviation * 0.9, desiredStandardDeviation * 1.1); + decimal value = r.GaussianDecimal(desiredMean, desiredStandardDeviation); + sum += value; + dataPoints[i] = value; } + double mean = (double) (sum / desiredSampleSize); + console.WriteLine($"Desired Mean: {desiredMean}; Actual Mean: {mean}"); + + // Must be within tolerance of 10% + mean.Should().BeInRange(desiredMean * 0.9d, desiredMean * 1.1d); - /// - /// Given a reasonable number of generated random numbers using the Gaussian methods, the mean and - /// standard deviation of those generated numbers should be very close the mean and standard deviation - /// that was specified when generating those numbers. - /// - /// - /// Because we can't expect the mean and standard deviation to match exactly, we allow a 10% tolerance. - /// - [Fact] - public void generated_ints_should_match_specified_parameters() + // Calculate the Standard Deviation, now that we have the mean + double sumSquares = 0; + for (int i = 0; i < desiredSampleSize; i++) { - double desiredMean = 105.5d; - double desiredStandardDeviation = 11.2d; - int desiredSampleSize = 1000; - int sum = 0; - int[] dataPoints = new int[desiredSampleSize]; - - for (int i = 0; i < desiredSampleSize; i++) - { - int value = r.GaussianInt(desiredMean, desiredStandardDeviation); - sum += value; - dataPoints[i] = value; - } - - double mean = (double) sum / desiredSampleSize; - console.WriteLine($"Desired Mean: {desiredMean}; Actual Mean: {mean}"); - - // Must be within tolerance of 10% - mean.Should().BeInRange(desiredMean * 0.9, desiredMean * 1.1); - - // Calculate the Standard Deviation, now that we have the mean - double sumSquares = 0; - for (int i = 0; i < desiredSampleSize; i++) - { - sumSquares += (dataPoints[i] - mean) * (dataPoints[i] - mean); - } - - double standardDeviation = Math.Sqrt(sumSquares / desiredSampleSize); - console.WriteLine( - $"Desired Standard Deviation: {desiredStandardDeviation}; Actual Standard Deviation {standardDeviation}"); - - // Must be withing a tolerance of 10% - standardDeviation.Should().BeInRange(desiredStandardDeviation * 0.9, desiredStandardDeviation * 1.1); + sumSquares += ((double) dataPoints[i] - mean) * ((double) dataPoints[i] - mean); + } + + double standardDeviation = Math.Sqrt(sumSquares / desiredSampleSize); + console.WriteLine( + $"Desired Standard Deviation: {desiredStandardDeviation}; Actual Standard Deviation {standardDeviation}"); + + // Must be withing a tolerance of 10% + standardDeviation.Should().BeInRange(desiredStandardDeviation * 0.9, desiredStandardDeviation * 1.1); + } + + + /// + /// Given a reasonable number of generated random numbers using the Gaussian methods, the mean and + /// standard deviation of those generated numbers should be very close the mean and standard deviation + /// that was specified when generating those numbers. + /// + /// + /// Because we can't expect the mean and standard deviation to match exactly, we allow a 10% tolerance. + /// + [Fact] + public void generated_ints_should_match_specified_parameters() + { + double desiredMean = 105.5d; + double desiredStandardDeviation = 11.2d; + int desiredSampleSize = 1000; + int sum = 0; + int[] dataPoints = new int[desiredSampleSize]; + for (int i = 0; i < desiredSampleSize; i++) + { + int value = r.GaussianInt(desiredMean, desiredStandardDeviation); + sum += value; + dataPoints[i] = value; } + double mean = (double) sum / desiredSampleSize; + console.WriteLine($"Desired Mean: {desiredMean}; Actual Mean: {mean}"); + + // Must be within tolerance of 10% + mean.Should().BeInRange(desiredMean * 0.9, desiredMean * 1.1); - /// - /// Given a reasonable number of generated random numbers using the Gaussian methods, the mean and - /// standard deviation of those generated numbers should be very close the mean and standard deviation - /// that was specified when generating those numbers. - /// - /// - /// Because we can't expect the mean and standard deviation to match exactly, we allow a 10% tolerance. - /// - [Fact] - public void generated_floats_should_match_specified_parameters() + // Calculate the Standard Deviation, now that we have the mean + double sumSquares = 0; + for (int i = 0; i < desiredSampleSize; i++) { - double desiredMean = 105.5d; - double desiredStandardDeviation = 11.2d; - int desiredSampleSize = 1000; - float sum = 0; - float[] dataPoints = new float[desiredSampleSize]; - - for (int i = 0; i < desiredSampleSize; i++) - { - float value = r.GaussianFloat(desiredMean, desiredStandardDeviation); - sum += value; - dataPoints[i] = value; - } - - double mean = sum / desiredSampleSize; - console.WriteLine($"Desired Mean: {desiredMean}; Actual Mean: {mean}"); - - // Must be within tolerance of 10% - mean.Should().BeInRange(desiredMean * 0.9d, desiredMean * 1.1d); - - // Calculate the Standard Deviation, now that we have the mean - double sumSquares = 0; - for (int i = 0; i < desiredSampleSize; i++) - { - sumSquares += ((double)dataPoints[i] - mean) * ((double)dataPoints[i] - mean); - } - - double standardDeviation = Math.Sqrt(sumSquares / desiredSampleSize); - console.WriteLine( - $"Desired Standard Deviation: {desiredStandardDeviation}; Actual Standard Deviation {standardDeviation}"); - - // Must be withing a tolerance of 10% - standardDeviation.Should().BeInRange(desiredStandardDeviation * 0.9, desiredStandardDeviation * 1.1); + sumSquares += (dataPoints[i] - mean) * (dataPoints[i] - mean); } - + + double standardDeviation = Math.Sqrt(sumSquares / desiredSampleSize); + console.WriteLine( + $"Desired Standard Deviation: {desiredStandardDeviation}; Actual Standard Deviation {standardDeviation}"); + + // Must be withing a tolerance of 10% + standardDeviation.Should().BeInRange(desiredStandardDeviation * 0.9, desiredStandardDeviation * 1.1); + + } + + + /// + /// Given a reasonable number of generated random numbers using the Gaussian methods, the mean and + /// standard deviation of those generated numbers should be very close the mean and standard deviation + /// that was specified when generating those numbers. + /// + /// + /// Because we can't expect the mean and standard deviation to match exactly, we allow a 10% tolerance. + /// + [Fact] + public void generated_floats_should_match_specified_parameters() + { + double desiredMean = 105.5d; + double desiredStandardDeviation = 11.2d; + int desiredSampleSize = 1000; + float sum = 0; + float[] dataPoints = new float[desiredSampleSize]; + + for (int i = 0; i < desiredSampleSize; i++) + { + float value = r.GaussianFloat(desiredMean, desiredStandardDeviation); + sum += value; + dataPoints[i] = value; + } + + double mean = sum / desiredSampleSize; + console.WriteLine($"Desired Mean: {desiredMean}; Actual Mean: {mean}"); + + // Must be within tolerance of 10% + mean.Should().BeInRange(desiredMean * 0.9d, desiredMean * 1.1d); + + // Calculate the Standard Deviation, now that we have the mean + double sumSquares = 0; + for (int i = 0; i < desiredSampleSize; i++) + { + sumSquares += ((double)dataPoints[i] - mean) * ((double)dataPoints[i] - mean); + } + + double standardDeviation = Math.Sqrt(sumSquares / desiredSampleSize); + console.WriteLine( + $"Desired Standard Deviation: {desiredStandardDeviation}; Actual Standard Deviation {standardDeviation}"); + + // Must be withing a tolerance of 10% + standardDeviation.Should().BeInRange(desiredStandardDeviation * 0.9, desiredStandardDeviation * 1.1); } + } diff --git a/Source/Bogus.Tests/ExtensionTests/ExtensionTest.cs b/Source/Bogus.Tests/ExtensionTests/ExtensionTest.cs index 0e5d392b..edffcd1f 100644 --- a/Source/Bogus.Tests/ExtensionTests/ExtensionTest.cs +++ b/Source/Bogus.Tests/ExtensionTests/ExtensionTest.cs @@ -6,280 +6,279 @@ using System; using Xunit; -namespace Bogus.Tests.ExtensionTests -{ - public class ExtensionTest : SeededTest +namespace Bogus.Tests.ExtensionTests; + + public class ExtensionTest : SeededTest + { + [Fact] + public void can_create_sortcode() + { + var f = new Finance(); + f.SortCode().Should().Be("61-86-06"); + f.SortCode(false).Should().Be("064391"); + } + + [Fact] + public void can_create_nino() + { + var f = new Finance(); + var nino = f.Nino(false); + var regex = @"^[A-CEGHJ-PR-TW-Z][A-CEGHJ-NPR-TW-Z][0-9]{2}[0-9]{2}[0-9]{2}[ABCD]"; + nino.Should().MatchRegex(regex); + } + + [Fact] + public void can_create_separated_nino() + { + var f = new Finance(); + var nino = f.Nino(); + var regex = @"^[A-CEGHJ-PR-TW-Z][A-CEGHJ-NPR-TW-Z]\s[0-9]{2}\s[0-9]{2}\s[0-9]{2}\s[ABCD]"; + nino.Should().MatchRegex(regex); + } + + [Fact] + public void can_create_codice_fiscale() + { + var f = new Faker("it"); + var codiceFiscale = f.Person.CodiceFiscale(); + codiceFiscale.Should().MatchRegex("^[A-Z]{2}[A-ZX][A-Z]{2}[A-ZX][0-9]{2}[A-Z][0-9]{2}[A-Z][0-9]{3}[A-Z]$"); + } + + [Fact] + public void codice_fiscale_is_16_chars_long() + { + var f = new Faker("it"); + var person = f.Person; + + var codiceFiscale = person.CodiceFiscale(); + + codiceFiscale.Should().HaveLength(16); + } + + [Fact] + public void codice_fiscale_generated_twice_are_equal() + { + var f = new Faker("it"); + var person = f.Person; + + var codiceFiscale1 = person.CodiceFiscale(); + var codiceFiscale2 = person.CodiceFiscale(); + + codiceFiscale1.Should().Be(codiceFiscale2); + } + + [Fact] + public void codice_fiscale_day_part_is_birthday_plus_40_for_females() + { + var f = new Faker("it"); + var person = f.Person; + + person.Gender = Name.Gender.Female; //force female gender + person.DateOfBirth = new DateTime(2010, 5, 13); + var codiceFiscale = person.CodiceFiscale(); + var dayPart = codiceFiscale.Substring(9, 2); + var dayPartAsInt = Convert.ToInt16(dayPart); + + dayPartAsInt.Should().Be(53); + } + + [Fact] + public void codice_fiscale_day_part_is_birthday_for_males() + { + var f = new Faker("it"); + var person = f.Person; + + person.Gender = Name.Gender.Male; //force male gender + person.DateOfBirth = new DateTime(2010, 5, 13); + var codiceFiscale = person.CodiceFiscale(); + var dayPart = codiceFiscale.Substring(9, 2); + var dayPartAsInt = Convert.ToInt16(dayPart); + + dayPartAsInt.Should().Be(13); + } + + [Fact] + public void codice_fiscale_is_case_insensitive() + { + var f = new Faker("it"); + var person = f.Person; + + person.FirstName = person.FirstName.ToUpper(); + person.LastName = person.LastName.ToUpper(); + var codiceFiscaleUpper = person.CodiceFiscale(); + person.FirstName = person.FirstName.ToLower(); + person.LastName = person.LastName.ToLower(); + var codiceFiscaleLower = person.CodiceFiscale(); + + codiceFiscaleUpper.Should().Be(codiceFiscaleLower); + } + + [Fact] + public void double_names_are_correctly_squeezed() + { + var f = new Faker("it"); + var person = f.Person; + + person.FirstName = "Bice Mia"; //force first name + person.LastName = "Alex Bea"; //force last name + var codiceFiscale = person.CodiceFiscale(); + + codiceFiscale.Should().StartWith("LXBBCM"); + } + + [Fact] + public void more_than_three_consonants_in_first_name_are_squeezed() + { + var f = new Faker("it"); + var person = f.Person; + + person.FirstName = "Annamaria"; + person.LastName = "Masi"; + var codiceFiscale = person.CodiceFiscale(); + + codiceFiscale.Should().MatchRegex("^.{3}NMR"); + } + + [Fact] + public void more_than_three_consonants_in_last_name_are_squeezed() + { + var f = new Faker("it"); + var person = f.Person; + + person.FirstName = "Michela"; + person.LastName = "Astratto"; + var codiceFiscale = person.CodiceFiscale(); + + codiceFiscale.Should().StartWith("STR"); + } + + [Fact] + public void names_starting_with_vowel_are_squeezed() + { + var f = new Faker("it"); + var person = f.Person; + + person.FirstName = "EULA"; + person.LastName = "AIRONE"; + var codiceFiscale = person.CodiceFiscale(); + + codiceFiscale.Should().StartWith("RNALEU"); + } + + [Fact] + public void names_with_apostrophe_are_squeezed() + { + var f = new Faker("it"); + var person = f.Person; + + person.FirstName = "Morena"; + person.LastName = "D'Urzo"; + var codiceFiscale = person.CodiceFiscale(); + + codiceFiscale.Should().StartWith("DRZMRN"); + } + + [Fact] + public void names_with_symbols_are_squeezed() + { + var f = new Faker("it"); + var person = f.Person; + + person.FirstName = "Pasquale"; + person.LastName = "D'Ama-Deidda"; + var codiceFiscale = person.CodiceFiscale(); + + codiceFiscale.Should().StartWith("DMDPQL"); + } + + [Fact] + public void names_with_one_consonant_are_squeezed() + { + var f = new Faker("it"); + var person = f.Person; + + person.FirstName = "Maia"; + person.LastName = "Aria"; + var codiceFiscale = person.CodiceFiscale(); + + codiceFiscale.Should().StartWith("RAIMAI"); + } + + [Fact] + public void names_with_three_consonants_are_squeezed() + { + var f = new Faker("it"); + var person = f.Person; + + person.FirstName = "Michi"; + person.LastName = "Macchi"; + var codiceFiscale = person.CodiceFiscale(); + + codiceFiscale.Should().StartWith("MCCMCH"); + } + + [Fact] + public void names_with_two_consonants_are_squeezed() + { + var f = new Faker("it"); + var person = f.Person; + + person.FirstName = "Nico"; + person.LastName = "Masi"; + var codiceFiscale = person.CodiceFiscale(); + + codiceFiscale.Should().StartWith("MSANCI"); + } + + [Fact] + public void names_with_two_letters_are_squeezed() + { + var f = new Faker("it"); + var person = f.Person; + + person.FirstName = "Ka"; + person.LastName = "Ro"; + var codiceFiscale = person.CodiceFiscale(); + + codiceFiscale.Should().StartWith("ROXKAX"); + } + + [Fact] + public void codice_fiscale_can_be_computed_from_finance_class() + { + var f = new Faker("it"); + + var codiceFiscale = f.Finance.CodiceFiscale("Rossi", "Mario", new DateTime(1990, 4, 23), true); + + codiceFiscale.Should().StartWith("RSSMRA90D23"); + } + [Fact] + public void nif_generator_for_person() { - [Fact] - public void can_create_sortcode() - { - var f = new Finance(); - f.SortCode().Should().Be("61-86-06"); - f.SortCode(false).Should().Be("064391"); - } - - [Fact] - public void can_create_nino() - { - var f = new Finance(); - var nino = f.Nino(false); - var regex = @"^[A-CEGHJ-PR-TW-Z][A-CEGHJ-NPR-TW-Z][0-9]{2}[0-9]{2}[0-9]{2}[ABCD]"; - nino.Should().MatchRegex(regex); - } - - [Fact] - public void can_create_separated_nino() - { - var f = new Finance(); - var nino = f.Nino(); - var regex = @"^[A-CEGHJ-PR-TW-Z][A-CEGHJ-NPR-TW-Z]\s[0-9]{2}\s[0-9]{2}\s[0-9]{2}\s[ABCD]"; - nino.Should().MatchRegex(regex); - } - - [Fact] - public void can_create_codice_fiscale() - { - var f = new Faker("it"); - var codiceFiscale = f.Person.CodiceFiscale(); - codiceFiscale.Should().MatchRegex("^[A-Z]{2}[A-ZX][A-Z]{2}[A-ZX][0-9]{2}[A-Z][0-9]{2}[A-Z][0-9]{3}[A-Z]$"); - } - - [Fact] - public void codice_fiscale_is_16_chars_long() - { - var f = new Faker("it"); - var person = f.Person; - - var codiceFiscale = person.CodiceFiscale(); - - codiceFiscale.Should().HaveLength(16); - } - - [Fact] - public void codice_fiscale_generated_twice_are_equal() - { - var f = new Faker("it"); - var person = f.Person; - - var codiceFiscale1 = person.CodiceFiscale(); - var codiceFiscale2 = person.CodiceFiscale(); - - codiceFiscale1.Should().Be(codiceFiscale2); - } - - [Fact] - public void codice_fiscale_day_part_is_birthday_plus_40_for_females() - { - var f = new Faker("it"); - var person = f.Person; - - person.Gender = Name.Gender.Female; //force female gender - person.DateOfBirth = new DateTime(2010, 5, 13); - var codiceFiscale = person.CodiceFiscale(); - var dayPart = codiceFiscale.Substring(9, 2); - var dayPartAsInt = Convert.ToInt16(dayPart); - - dayPartAsInt.Should().Be(53); - } - - [Fact] - public void codice_fiscale_day_part_is_birthday_for_males() - { - var f = new Faker("it"); - var person = f.Person; - - person.Gender = Name.Gender.Male; //force male gender - person.DateOfBirth = new DateTime(2010, 5, 13); - var codiceFiscale = person.CodiceFiscale(); - var dayPart = codiceFiscale.Substring(9, 2); - var dayPartAsInt = Convert.ToInt16(dayPart); - - dayPartAsInt.Should().Be(13); - } - - [Fact] - public void codice_fiscale_is_case_insensitive() - { - var f = new Faker("it"); - var person = f.Person; - - person.FirstName = person.FirstName.ToUpper(); - person.LastName = person.LastName.ToUpper(); - var codiceFiscaleUpper = person.CodiceFiscale(); - person.FirstName = person.FirstName.ToLower(); - person.LastName = person.LastName.ToLower(); - var codiceFiscaleLower = person.CodiceFiscale(); - - codiceFiscaleUpper.Should().Be(codiceFiscaleLower); - } - - [Fact] - public void double_names_are_correctly_squeezed() - { - var f = new Faker("it"); - var person = f.Person; - - person.FirstName = "Bice Mia"; //force first name - person.LastName = "Alex Bea"; //force last name - var codiceFiscale = person.CodiceFiscale(); - - codiceFiscale.Should().StartWith("LXBBCM"); - } - - [Fact] - public void more_than_three_consonants_in_first_name_are_squeezed() - { - var f = new Faker("it"); - var person = f.Person; - - person.FirstName = "Annamaria"; - person.LastName = "Masi"; - var codiceFiscale = person.CodiceFiscale(); - - codiceFiscale.Should().MatchRegex("^.{3}NMR"); - } - - [Fact] - public void more_than_three_consonants_in_last_name_are_squeezed() - { - var f = new Faker("it"); - var person = f.Person; - - person.FirstName = "Michela"; - person.LastName = "Astratto"; - var codiceFiscale = person.CodiceFiscale(); - - codiceFiscale.Should().StartWith("STR"); - } - - [Fact] - public void names_starting_with_vowel_are_squeezed() - { - var f = new Faker("it"); - var person = f.Person; - - person.FirstName = "EULA"; - person.LastName = "AIRONE"; - var codiceFiscale = person.CodiceFiscale(); - - codiceFiscale.Should().StartWith("RNALEU"); - } - - [Fact] - public void names_with_apostrophe_are_squeezed() - { - var f = new Faker("it"); - var person = f.Person; - - person.FirstName = "Morena"; - person.LastName = "D'Urzo"; - var codiceFiscale = person.CodiceFiscale(); - - codiceFiscale.Should().StartWith("DRZMRN"); - } - - [Fact] - public void names_with_symbols_are_squeezed() - { - var f = new Faker("it"); - var person = f.Person; - - person.FirstName = "Pasquale"; - person.LastName = "D'Ama-Deidda"; - var codiceFiscale = person.CodiceFiscale(); - - codiceFiscale.Should().StartWith("DMDPQL"); - } - - [Fact] - public void names_with_one_consonant_are_squeezed() - { - var f = new Faker("it"); - var person = f.Person; - - person.FirstName = "Maia"; - person.LastName = "Aria"; - var codiceFiscale = person.CodiceFiscale(); - - codiceFiscale.Should().StartWith("RAIMAI"); - } - - [Fact] - public void names_with_three_consonants_are_squeezed() - { - var f = new Faker("it"); - var person = f.Person; - - person.FirstName = "Michi"; - person.LastName = "Macchi"; - var codiceFiscale = person.CodiceFiscale(); - - codiceFiscale.Should().StartWith("MCCMCH"); - } - - [Fact] - public void names_with_two_consonants_are_squeezed() - { - var f = new Faker("it"); - var person = f.Person; - - person.FirstName = "Nico"; - person.LastName = "Masi"; - var codiceFiscale = person.CodiceFiscale(); - - codiceFiscale.Should().StartWith("MSANCI"); - } - - [Fact] - public void names_with_two_letters_are_squeezed() - { - var f = new Faker("it"); - var person = f.Person; - - person.FirstName = "Ka"; - person.LastName = "Ro"; - var codiceFiscale = person.CodiceFiscale(); - - codiceFiscale.Should().StartWith("ROXKAX"); - } - - [Fact] - public void codice_fiscale_can_be_computed_from_finance_class() - { - var f = new Faker("it"); - - var codiceFiscale = f.Finance.CodiceFiscale("Rossi", "Mario", new DateTime(1990, 4, 23), true); - - codiceFiscale.Should().StartWith("RSSMRA90D23"); - } - [Fact] - public void nif_generator_for_person() - { - //Arrange - var regex = @"^[0-9]{9}$"; - var f = new Faker("pt_PT"); - var person = f.Person; - - //Act - var nifNumber = person.Nif(); - - //Assert - nifNumber.Should().MatchRegex(regex).And.HaveLength(9).And.Match(p => p.Substring(0, 1) == "1" || p.Substring(0, 1) == "2"); - } - - [Fact] - public void nif_generator_for_company() - { - //Arrange - var regex = @"^[0-9]{9}$"; - var f = new Faker("pt_PT"); - var company = f.Company; - - //Act - var nipcNumber = company.Nipc(); - - //Assert - nipcNumber.Should().MatchRegex(regex).And.HaveLength(9).And.Match(p => p.Substring(0, 1) == "5" || p.Substring(0, 1) == "6" || p.Substring(0, 1) == "8" || p.Substring(0, 1) == "9"); - } - } + //Arrange + var regex = @"^[0-9]{9}$"; + var f = new Faker("pt_PT"); + var person = f.Person; + + //Act + var nifNumber = person.Nif(); + + //Assert + nifNumber.Should().MatchRegex(regex).And.HaveLength(9).And.Match(p => p.Substring(0, 1) == "1" || p.Substring(0, 1) == "2"); + } + + [Fact] + public void nif_generator_for_company() + { + //Arrange + var regex = @"^[0-9]{9}$"; + var f = new Faker("pt_PT"); + var company = f.Company; + + //Act + var nipcNumber = company.Nipc(); + + //Assert + nipcNumber.Should().MatchRegex(regex).And.HaveLength(9).And.Match(p => p.Substring(0, 1) == "5" || p.Substring(0, 1) == "6" || p.Substring(0, 1) == "8" || p.Substring(0, 1) == "9"); + } } diff --git a/Source/Bogus.Tests/ExtensionTests/NorwegianExtensionTest.cs b/Source/Bogus.Tests/ExtensionTests/NorwegianExtensionTest.cs index 53ea97f8..6ab8252c 100644 --- a/Source/Bogus.Tests/ExtensionTests/NorwegianExtensionTest.cs +++ b/Source/Bogus.Tests/ExtensionTests/NorwegianExtensionTest.cs @@ -3,108 +3,107 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.ExtensionTests +namespace Bogus.Tests.ExtensionTests; + +public class NorwegianExtensionTest : SeededTest { - public class NorwegianExtensionTest : SeededTest + private void IsLegalIndividualNumber(int readIndNo, int birthYear, Person p) { - private void IsLegalIndividualNumber(int readIndNo, int birthYear, Person p) + // Check that birth year is in the correct range given individual number. + if (0 <= readIndNo && readIndNo <= 499) { - // Check that birth year is in the correct range given individual number. - if (0 <= readIndNo && readIndNo <= 499) - { - birthYear.Should().BeInRange(0, 99); - } - else if (750 <= readIndNo && readIndNo <= 999) + birthYear.Should().BeInRange(0, 99); + } + else if (750 <= readIndNo && readIndNo <= 999) + { + birthYear.Should().BeInRange(0, 39); + } + else if (500 <= readIndNo && readIndNo <= 749) + { + if (0 <= birthYear && birthYear <= 39) { birthYear.Should().BeInRange(0, 39); } - else if (500 <= readIndNo && readIndNo <= 749) - { - if (0 <= birthYear && birthYear <= 39) - { - birthYear.Should().BeInRange(0, 39); - } - else - { - birthYear.Should().BeInRange(54, 99); - } - } - - // Check odd/even individual number given gender. - if (p.Gender == Name.Gender.Female) - { - (readIndNo % 2 == 0).Should().BeTrue(); - } else { - (readIndNo % 2 == 0).Should().BeFalse(); + birthYear.Should().BeInRange(54, 99); } } - private void IsLegalChecksum(string readFødselsnummer) + // Check odd/even individual number given gender. + if (p.Gender == Name.Gender.Female) { - string readCs = readFødselsnummer.Substring(9, 2); - - int d1 = int.Parse(readFødselsnummer.Substring(0, 1)); - int d2 = int.Parse(readFødselsnummer.Substring(1, 1)); - int m1 = int.Parse(readFødselsnummer.Substring(2, 1)); - int m2 = int.Parse(readFødselsnummer.Substring(3, 1)); - int y1 = int.Parse(readFødselsnummer.Substring(4, 1)); - int y2 = int.Parse(readFødselsnummer.Substring(5, 1)); - int i1 = int.Parse(readFødselsnummer.Substring(6, 1)); - int i2 = int.Parse(readFødselsnummer.Substring(7, 1)); - int i3 = int.Parse(readFødselsnummer.Substring(8, 1)); - - int cs1 = 11 - (((3 * d1) + (7 * d2) + (6 * m1) + (1 * m2) + (8 * y1) + (9 * y2) + (4 * i1) + (5 * i2) + (2 * i3)) % 11); - int cs2 = 11 - (((5 * d1) + (4 * d2) + (3 * m1) + (2 * m2) + (7 * y1) + (6 * y2) + (5 * i1) + (4 * i2) + (3 * i3) + (2 * cs1)) % 11); - - if (cs1 == 11) - { - cs1 = 0; - } - - if (cs2 == 11) - { - cs2 = 0; - } + (readIndNo % 2 == 0).Should().BeTrue(); + } + else + { + (readIndNo % 2 == 0).Should().BeFalse(); + } + } - $"{cs1}{cs2}".Should().Be(readCs); + private void IsLegalChecksum(string readFødselsnummer) + { + string readCs = readFødselsnummer.Substring(9, 2); + + int d1 = int.Parse(readFødselsnummer.Substring(0, 1)); + int d2 = int.Parse(readFødselsnummer.Substring(1, 1)); + int m1 = int.Parse(readFødselsnummer.Substring(2, 1)); + int m2 = int.Parse(readFødselsnummer.Substring(3, 1)); + int y1 = int.Parse(readFødselsnummer.Substring(4, 1)); + int y2 = int.Parse(readFødselsnummer.Substring(5, 1)); + int i1 = int.Parse(readFødselsnummer.Substring(6, 1)); + int i2 = int.Parse(readFødselsnummer.Substring(7, 1)); + int i3 = int.Parse(readFødselsnummer.Substring(8, 1)); + + int cs1 = 11 - (((3 * d1) + (7 * d2) + (6 * m1) + (1 * m2) + (8 * y1) + (9 * y2) + (4 * i1) + (5 * i2) + (2 * i3)) % 11); + int cs2 = 11 - (((5 * d1) + (4 * d2) + (3 * m1) + (2 * m2) + (7 * y1) + (6 * y2) + (5 * i1) + (4 * i2) + (3 * i3) + (2 * cs1)) % 11); + + if (cs1 == 11) + { + cs1 = 0; } - private void IsLegalFødselsnummer(string readFødselsnummer, Person p) + if (cs2 == 11) { - readFødselsnummer.Should().HaveLength(11); + cs2 = 0; + } - int birthYear = int.Parse(readFødselsnummer.Substring(4, 2)); - int indNo = int.Parse(readFødselsnummer.Substring(6, 3)); + $"{cs1}{cs2}".Should().Be(readCs); + } - IsLegalIndividualNumber(indNo, birthYear, p); - IsLegalChecksum(readFødselsnummer); - } + private void IsLegalFødselsnummer(string readFødselsnummer, Person p) + { + readFødselsnummer.Should().HaveLength(11); - [Fact] - public void can_create_norwegian_fødselsnummer() - { - var f = new Faker("nb_NO"); - var person = f.Person; + int birthYear = int.Parse(readFødselsnummer.Substring(4, 2)); + int indNo = int.Parse(readFødselsnummer.Substring(6, 3)); - string fødselsnummer = person.Fødselsnummer(); + IsLegalIndividualNumber(indNo, birthYear, p); + IsLegalChecksum(readFødselsnummer); + } - IsLegalFødselsnummer(fødselsnummer, person); - } + [Fact] + public void can_create_norwegian_fødselsnummer() + { + var f = new Faker("nb_NO"); + var person = f.Person; - [Fact] - public void can_create_correct_checksum_1() - { - // Test fødselsnummer from DSF. - IsLegalChecksum("31080700442"); - } + string fødselsnummer = person.Fødselsnummer(); - [Fact] - public void can_create_correct_checksum_2() - { - // Test fødselsnummer from DSF. - IsLegalChecksum("10050050489"); - } + IsLegalFødselsnummer(fødselsnummer, person); + } + + [Fact] + public void can_create_correct_checksum_1() + { + // Test fødselsnummer from DSF. + IsLegalChecksum("31080700442"); + } + + [Fact] + public void can_create_correct_checksum_2() + { + // Test fødselsnummer from DSF. + IsLegalChecksum("10050050489"); } } diff --git a/Source/Bogus.Tests/ExtensionTests/RegistrationPlateExtensionsForGreatBritainTests.cs b/Source/Bogus.Tests/ExtensionTests/RegistrationPlateExtensionsForGreatBritainTests.cs index c4238d24..35fd4198 100644 --- a/Source/Bogus.Tests/ExtensionTests/RegistrationPlateExtensionsForGreatBritainTests.cs +++ b/Source/Bogus.Tests/ExtensionTests/RegistrationPlateExtensionsForGreatBritainTests.cs @@ -6,111 +6,110 @@ using Xunit; using Xunit.Abstractions; -namespace Bogus.Tests.ExtensionTests +namespace Bogus.Tests.ExtensionTests; + +public class RegistrationPlateExtensionsForGreatBritainTests : SeededTest { - public class RegistrationPlateExtensionsForGreatBritainTests : SeededTest - { - private readonly ITestOutputHelper testOutputHelper; + private readonly ITestOutputHelper testOutputHelper; - public RegistrationPlateExtensionsForGreatBritainTests(ITestOutputHelper testOutputHelper) - { - this.testOutputHelper = testOutputHelper; - } + public RegistrationPlateExtensionsForGreatBritainTests(ITestOutputHelper testOutputHelper) + { + this.testOutputHelper = testOutputHelper; + } - [Fact] - public void reject_registration_date_before_current_style() - { - var vehicle = new Vehicle(); + [Fact] + public void reject_registration_date_before_current_style() + { + var vehicle = new Vehicle(); - Action a = () => vehicle.GbRegistrationPlate(new DateTime(2001, 8, 31), new DateTime(2019, 7, 5)); - a.Should().Throw() - .Where(ex => ex.Message.StartsWith("Can only accept registration dates between 2001-09-01 and 2051-02-28.")) - .Where(ex => ex.ParamName == "dateFrom"); - } + Action a = () => vehicle.GbRegistrationPlate(new DateTime(2001, 8, 31), new DateTime(2019, 7, 5)); + a.Should().Throw() + .Where(ex => ex.Message.StartsWith("Can only accept registration dates between 2001-09-01 and 2051-02-28.")) + .Where(ex => ex.ParamName == "dateFrom"); + } - [Fact] - public void reject_registration_date_after_current_style() - { - var vehicle = new Vehicle(); - Action a = () => vehicle.GbRegistrationPlate(new DateTime(2019, 7, 5), new DateTime(2051, 9, 1)); - a.Should().Throw() - .Where( ex => ex.Message.StartsWith("Can only accept registration dates between 2001-09-01 and 2051-02-28.")) - .Where( ex => ex.ParamName == "dateTo" ); - } + [Fact] + public void reject_registration_date_after_current_style() + { + var vehicle = new Vehicle(); + Action a = () => vehicle.GbRegistrationPlate(new DateTime(2019, 7, 5), new DateTime(2051, 9, 1)); + a.Should().Throw() + .Where( ex => ex.Message.StartsWith("Can only accept registration dates between 2001-09-01 and 2051-02-28.")) + .Where( ex => ex.ParamName == "dateTo" ); + } - [Fact] - public void date_expressed_wrong_way_around_still_works() - { - var vehicle = new Vehicle(); - var plate = vehicle.GbRegistrationPlate(new DateTime(2019, 8, 31), new DateTime(2019, 3, 1)); - plate.Substring(2, 2).Should().Be("19"); - } + [Fact] + public void date_expressed_wrong_way_around_still_works() + { + var vehicle = new Vehicle(); + var plate = vehicle.GbRegistrationPlate(new DateTime(2019, 8, 31), new DateTime(2019, 3, 1)); + plate.Substring(2, 2).Should().Be("19"); + } - [Fact] - public void early_part_of_year_is_has_age_holdover_from_previous_year() - { - var vehicle = new Vehicle(); - var plate = vehicle.GbRegistrationPlate(new DateTime(2019, 1, 1), new DateTime(2019, 2, 28)); - plate.Substring(2, 2).Should().Be("68"); - } + [Fact] + public void early_part_of_year_is_has_age_holdover_from_previous_year() + { + var vehicle = new Vehicle(); + var plate = vehicle.GbRegistrationPlate(new DateTime(2019, 1, 1), new DateTime(2019, 2, 28)); + plate.Substring(2, 2).Should().Be("68"); + } - [Fact] - public void mid_part_of_year_is_has_age_equivalent_to_two_digit_year() - { - var vehicle = new Vehicle(); - var plate = vehicle.GbRegistrationPlate(new DateTime(2009, 3, 1), new DateTime(2009, 8, 31)); - plate.Substring(2, 2).Should().Be("09"); - } + [Fact] + public void mid_part_of_year_is_has_age_equivalent_to_two_digit_year() + { + var vehicle = new Vehicle(); + var plate = vehicle.GbRegistrationPlate(new DateTime(2009, 3, 1), new DateTime(2009, 8, 31)); + plate.Substring(2, 2).Should().Be("09"); + } - [Fact] - public void end_part_of_year_is_has_age_equivalent_to_two_digit_year_offset_by_fifty() - { - var vehicle = new Vehicle(); - var plate = vehicle.GbRegistrationPlate(new DateTime(2009, 9, 1), new DateTime(2009, 12, 31)); - plate.Substring(2, 2).Should().Be("59"); - } + [Fact] + public void end_part_of_year_is_has_age_equivalent_to_two_digit_year_offset_by_fifty() + { + var vehicle = new Vehicle(); + var plate = vehicle.GbRegistrationPlate(new DateTime(2009, 9, 1), new DateTime(2009, 12, 31)); + plate.Substring(2, 2).Should().Be("59"); + } - [Fact] - public void new_licence_plate_on_each_generate() - { - var vehicle = new Vehicle(); - var plates = Enumerable - .Range(1,10) - .Select(_ => vehicle.GbRegistrationPlate(new DateTime(2001, 9, 1), new DateTime(2019, 7, 5))) - .ToArray(); + [Fact] + public void new_licence_plate_on_each_generate() + { + var vehicle = new Vehicle(); + var plates = Enumerable + .Range(1,10) + .Select(_ => vehicle.GbRegistrationPlate(new DateTime(2001, 9, 1), new DateTime(2019, 7, 5))) + .ToArray(); - testOutputHelper.WriteLine(string.Join(Environment.NewLine, plates)); - plates.Distinct().Count().Should().Be(plates.Length); - } + testOutputHelper.WriteLine(string.Join(Environment.NewLine, plates)); + plates.Distinct().Count().Should().Be(plates.Length); + } - [Fact] - public void edinburgh_mid2007_plates_have_exception_applied_to_them() - { - Randomizer.Seed = new Random(293); - var vehicle = new Vehicle(); - var plate = vehicle.GbRegistrationPlate(new DateTime(2007, 3, 1), new DateTime(2007, 8, 31)); - plate.Should().StartWith("TN07"); - } + [Fact] + public void edinburgh_mid2007_plates_have_exception_applied_to_them() + { + Randomizer.Seed = new Random(293); + var vehicle = new Vehicle(); + var plate = vehicle.GbRegistrationPlate(new DateTime(2007, 3, 1), new DateTime(2007, 8, 31)); + plate.Should().StartWith("TN07"); + } - [Theory] - [InlineData(1, "XE68")] - [InlineData(2, "XF68")] - [InlineData(3, "XA19")] - [InlineData(4, "XB19")] - [InlineData(5, "XC19")] - [InlineData(6, "XD19")] - [InlineData(7, "XE19")] - [InlineData(8, "XF19")] - [InlineData(9, "XA69")] - [InlineData(10, "XB69")] - [InlineData(11, "XC69")] - [InlineData(12, "XD69")] - public void export_plates_have_pseudo_location_marker_based_on_registration_date(int month, string partialPlate) - { - Randomizer.Seed = new Random(14); - var vehicle = new Vehicle(); - var plate = vehicle.GbRegistrationPlate(new DateTime(2019, month, 1), new DateTime(2019, month, DateTime.DaysInMonth(2019, month))); - plate.Should().StartWith(partialPlate); - } - } + [Theory] + [InlineData(1, "XE68")] + [InlineData(2, "XF68")] + [InlineData(3, "XA19")] + [InlineData(4, "XB19")] + [InlineData(5, "XC19")] + [InlineData(6, "XD19")] + [InlineData(7, "XE19")] + [InlineData(8, "XF19")] + [InlineData(9, "XA69")] + [InlineData(10, "XB69")] + [InlineData(11, "XC69")] + [InlineData(12, "XD69")] + public void export_plates_have_pseudo_location_marker_based_on_registration_date(int month, string partialPlate) + { + Randomizer.Seed = new Random(14); + var vehicle = new Vehicle(); + var plate = vehicle.GbRegistrationPlate(new DateTime(2019, month, 1), new DateTime(2019, month, DateTime.DaysInMonth(2019, month))); + plate.Should().StartWith(partialPlate); + } } diff --git a/Source/Bogus.Tests/ExtensionTests/SwedishExtensionTest.cs b/Source/Bogus.Tests/ExtensionTests/SwedishExtensionTest.cs index a5e91f4d..35cf0068 100644 --- a/Source/Bogus.Tests/ExtensionTests/SwedishExtensionTest.cs +++ b/Source/Bogus.Tests/ExtensionTests/SwedishExtensionTest.cs @@ -4,66 +4,65 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.ExtensionTests +namespace Bogus.Tests.ExtensionTests; + +public class SwedishExtensionTest : SeededTest { - public class SwedishExtensionTest : SeededTest + [Fact] + public void can_create_valid_swedish_personnummer() { - [Fact] - public void can_create_valid_swedish_personnummer() - { - var f = new Faker("sv"); - var person = f.Person; + var f = new Faker("sv"); + var person = f.Person; - var personnummer = person.Personnummer(); + var personnummer = person.Personnummer(); - CheckLuhn(personnummer.Substring(2)).Should().BeTrue(); - } + CheckLuhn(personnummer.Substring(2)).Should().BeTrue(); + } - [Fact] - public void when_person_is_male_second_last_number_is_even() - { - var f = new Faker("sv"); - var person = f.Person; - person.Gender = Name.Gender.Male; + [Fact] + public void when_person_is_male_second_last_number_is_even() + { + var f = new Faker("sv"); + var person = f.Person; + person.Gender = Name.Gender.Male; - var personnummer = person.Personnummer(); + var personnummer = person.Personnummer(); - var secondLast = int.Parse(personnummer.Substring(personnummer.Length - 2, 1)); + var secondLast = int.Parse(personnummer.Substring(personnummer.Length - 2, 1)); - secondLast.Should() - .Match(x => x % 2 == 0) - .And.BeLessThan(10) - .And.BeGreaterThan(0); - } + secondLast.Should() + .Match(x => x % 2 == 0) + .And.BeLessThan(10) + .And.BeGreaterThan(0); + } - [Fact] - public void when_person_is_female_second_last_number_is_odd() - { - var f = new Faker("sv"); - var person = f.Person; - person.Gender = Name.Gender.Female; + [Fact] + public void when_person_is_female_second_last_number_is_odd() + { + var f = new Faker("sv"); + var person = f.Person; + person.Gender = Name.Gender.Female; - var personnummer = person.Personnummer(); + var personnummer = person.Personnummer(); - var secondLast = int.Parse(personnummer.Substring(personnummer.Length - 2, 1)); + var secondLast = int.Parse(personnummer.Substring(personnummer.Length - 2, 1)); - secondLast.Should() - .Match(x => x % 2 == 1) - .And.BeLessThan(10) - .And.BeGreaterThan(0); - } + secondLast.Should() + .Match(x => x % 2 == 1) + .And.BeLessThan(10) + .And.BeGreaterThan(0); + } - private static bool CheckLuhn(string digits) - { - return digits.All(char.IsDigit) && digits.Reverse() - .Select(c => c - 48) - .Select( - (thisNum, i) => i % 2 == 0 - ? thisNum - : ((thisNum *= 2) > 9 ? thisNum - 9 : thisNum) - ) - .Sum() % 10 == 0; - } + private static bool CheckLuhn(string digits) + { + return digits.All(char.IsDigit) && digits.Reverse() + .Select(c => c - 48) + .Select( + (thisNum, i) => i % 2 == 0 + ? thisNum + : ((thisNum *= 2) > 9 ? thisNum - 9 : thisNum) + ) + .Sum() % 10 == 0; } } \ No newline at end of file diff --git a/Source/Bogus.Tests/ExtensionsForTesting.cs b/Source/Bogus.Tests/ExtensionsForTesting.cs index 1ecd3010..a80f6b58 100644 --- a/Source/Bogus.Tests/ExtensionsForTesting.cs +++ b/Source/Bogus.Tests/ExtensionsForTesting.cs @@ -2,23 +2,22 @@ using Newtonsoft.Json; using Xunit.Abstractions; -namespace Bogus.Tests +namespace Bogus.Tests; + +public static class ExtensionsForTesting { - public static class ExtensionsForTesting + public static void Dump(this object obj) { - public static void Dump(this object obj) - { - Console.WriteLine(obj.DumpString()); - } + Console.WriteLine(obj.DumpString()); + } - public static string DumpString(this object obj) - { - return JsonConvert.SerializeObject(obj, Formatting.Indented); - } + public static string DumpString(this object obj) + { + return JsonConvert.SerializeObject(obj, Formatting.Indented); + } - public static void Dump(this ITestOutputHelper console, object obj) - { - console.WriteLine(obj.DumpString()); - } + public static void Dump(this ITestOutputHelper console, object obj) + { + console.WriteLine(obj.DumpString()); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/FluentTests.cs b/Source/Bogus.Tests/FluentTests.cs index 73e891fa..75a850fc 100644 --- a/Source/Bogus.Tests/FluentTests.cs +++ b/Source/Bogus.Tests/FluentTests.cs @@ -6,416 +6,415 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests +namespace Bogus.Tests; + +public class Examples : SeededTest { - public class Examples : SeededTest + [Fact] + public void TestAPIDesign() { - [Fact] - public void TestAPIDesign() - { - //Set the randomzier seed if you wish to generate repeatable data sets. - Randomizer.Seed = new Random(3897234); - - var fruit = new[] {"apple", "banana", "orange", "strawberry", "kiwi"}; - - var orderIds = 0; - var testOrders = new Faker() - //Ensure all properties have rules. By default, StrictMode is false - //Set a global policy by using Faker.DefaultStrictMode if you prefer. - .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() - //Optional: Call for objects that have complex initialization - .CustomInstantiator(f => new User(userIds++, f.Random.Replace("###-##-####"))) - - //Basic rules using built-in generators - .RuleFor(u => u.FirstName, f => f.Name.FirstName()) - .RuleFor(u => u.LastName, f => f.Name.LastName()) - .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}") - .RuleFor(u => u.SomeGuid, Guid.NewGuid) - - //Use an enum outside scope. - .RuleFor(u => u.Gender, f => f.PickRandom()) - //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)) - //After all rules are applied finish with the following action - .FinishWith((f, u) => { Console.WriteLine("User Created! Name={0}", u.FullName); }); - - //RunAfter - //InvokeAfterRules - //FinalizeWith - //AfterRulesInvoke - //PostProcess - //InvokeAfterAll - //BeforeReturn - //FinallyInvoke - //FinishWith - - var user = testUsers.Generate(3); - - user.Dump(); - } - - [Fact] - public void Without_Fluent_Syntax() - { - var random = new Randomizer(); - var lorem = new Lorem("en"); - var o = new Order - { - OrderId = random.Number(1, 100), - Item = lorem.Sentence(), - Quantity = random.Number(1, 10) - }; - o.OrderId.Should().Be(61); - o.Quantity.Should().Be(7); - o.Dump(); - } + //Set the randomzier seed if you wish to generate repeatable data sets. + Randomizer.Seed = new Random(3897234); + + var fruit = new[] {"apple", "banana", "orange", "strawberry", "kiwi"}; + + var orderIds = 0; + var testOrders = new Faker() + //Ensure all properties have rules. By default, StrictMode is false + //Set a global policy by using Faker.DefaultStrictMode if you prefer. + .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() + //Optional: Call for objects that have complex initialization + .CustomInstantiator(f => new User(userIds++, f.Random.Replace("###-##-####"))) + + //Basic rules using built-in generators + .RuleFor(u => u.FirstName, f => f.Name.FirstName()) + .RuleFor(u => u.LastName, f => f.Name.LastName()) + .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}") + .RuleFor(u => u.SomeGuid, Guid.NewGuid) + + //Use an enum outside scope. + .RuleFor(u => u.Gender, f => f.PickRandom()) + //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)) + //After all rules are applied finish with the following action + .FinishWith((f, u) => { Console.WriteLine("User Created! Name={0}", u.FullName); }); + + //RunAfter + //InvokeAfterRules + //FinalizeWith + //AfterRulesInvoke + //PostProcess + //InvokeAfterAll + //BeforeReturn + //FinallyInvoke + //FinishWith + + var user = testUsers.Generate(3); + + user.Dump(); + } - [Fact] - public void With_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.OrderId.Should().Be(61); - o.Quantity.Should().Be(7); - o.Dump(); - } + [Fact] + public void Without_Fluent_Syntax() + { + var random = new Randomizer(); + var lorem = new Lorem("en"); + var o = new Order + { + OrderId = random.Number(1, 100), + Item = lorem.Sentence(), + Quantity = random.Number(1, 10) + }; + o.OrderId.Should().Be(61); + o.Quantity.Should().Be(7); + o.Dump(); + } - public class OrderFaker : Faker - { - public OrderFaker() : base("en") + [Fact] + public void With_Faker_Facade() + { + var faker = new Faker("en"); + var o = new Order { - 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)); - } - } + OrderId = faker.Random.Number(1, 100), + Item = faker.Lorem.Sentence(), + Quantity = faker.Random.Number(1, 10) + }; + o.OrderId.Should().Be(61); + o.Quantity.Should().Be(7); + o.Dump(); + } - [Fact] - public void Using_FakerT_Inheritance() + public class OrderFaker : Faker + { + public OrderFaker() : base("en") { - var orderFaker = new OrderFaker(); - var o = orderFaker.Generate(); - o.Dump(); + 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)); } + } - [Fact] - public void With_Korean_Locale() - { - var lorem = new Lorem(locale: "ko"); - Console.WriteLine(lorem.Sentence(5)); - } + [Fact] + public void Using_FakerT_Inheritance() + { + var orderFaker = new OrderFaker(); + var o = orderFaker.Generate(); + o.Dump(); + } - [Fact] - public void Create_Context_Related_Person() - { - var person = new Person(); + [Fact] + public void With_Korean_Locale() + { + var lorem = new Lorem(locale: "ko"); + Console.WriteLine(lorem.Sentence(5)); + } - person.Dump(); - } + [Fact] + public void Create_Context_Related_Person() + { + var person = new Person(); - [Fact] - public void Create_an_SSN() - { - var ssn = new Randomizer().Replace("###-##-####"); - ssn.Dump(); + person.Dump(); + } - var code = new Randomizer().Replace("##? ??? ####"); - code.Dump(); - } + [Fact] + public void Create_an_SSN() + { + var ssn = new Randomizer().Replace("###-##-####"); + ssn.Dump(); + var code = new Randomizer().Replace("##? ??? ####"); + code.Dump(); + } - [Fact] - public void Handlebar() - { - var faker = new Faker(); - var randomName = faker.Parse("{{name.lastName}}, {{name.firstName}} {{name.suffix}}"); - randomName.Dump(); - } - [Fact] - public void TestIgnore() - { - var faker = new Faker() - .StrictMode(true) - .Ignore(o => o.Item) - .Ignore(o => o.LotNumber) - .RuleFor(o => o.OrderId, f => 3343) - .RuleFor(o => o.Quantity, f => f.Random.Number(3)); + [Fact] + public void Handlebar() + { + var faker = new Faker(); + var randomName = faker.Parse("{{name.lastName}}, {{name.firstName}} {{name.suffix}}"); + randomName.Dump(); + } - var fake = faker.Generate(); + [Fact] + public void TestIgnore() + { + var faker = new Faker() + .StrictMode(true) + .Ignore(o => o.Item) + .Ignore(o => o.LotNumber) + .RuleFor(o => o.OrderId, f => 3343) + .RuleFor(o => o.Quantity, f => f.Random.Number(3)); - fake.Dump(); + var fake = faker.Generate(); - fake.Item.Should().BeNull(); - fake.LotNumber.Should().BeNull(); - } + fake.Dump(); - [Fact] - public void Can_Define_Rule_By_Type() - { - var faker = new Faker() - .RuleForType(typeof(string), f => f.Random.Word()); + fake.Item.Should().BeNull(); + fake.LotNumber.Should().BeNull(); + } - var fake = faker.Generate(); + [Fact] + public void Can_Define_Rule_By_Type() + { + var faker = new Faker() + .RuleForType(typeof(string), f => f.Random.Word()); - fake.Dump(); + var fake = faker.Generate(); - fake.Bake.Should().NotBeNullOrEmpty(); - fake.Make.Should().NotBeNullOrEmpty(); - fake.Fake.Should().NotBeNullOrEmpty(); - fake.Bar.Should().NotBeNullOrEmpty(); - fake.Foo.Should().NotBeNullOrEmpty(); - fake.Baz.Should().NotBeNullOrEmpty(); - } + fake.Dump(); - [Fact] - public void Should_Throw_Exception_If_RuleForType_Types_Dont_Match() - { - Action action = () => - { - var faker = new Faker() - .RuleForType(typeof(int), f => f.Random.Word()); - }; + fake.Bake.Should().NotBeNullOrEmpty(); + fake.Make.Should().NotBeNullOrEmpty(); + fake.Fake.Should().NotBeNullOrEmpty(); + fake.Bar.Should().NotBeNullOrEmpty(); + fake.Foo.Should().NotBeNullOrEmpty(); + fake.Baz.Should().NotBeNullOrEmpty(); + } - action.Should().Throw(); - } + [Fact] + public void Should_Throw_Exception_If_RuleForType_Types_Dont_Match() + { + Action action = () => + { + var faker = new Faker() + .RuleForType(typeof(int), f => f.Random.Word()); + }; - [Fact] - public void implicit_operator_test() - { - var orderFaker = new Faker() - .RuleFor(o => o.OrderId, f => f.IndexVariable++) - .RuleFor(o => o.Quantity, f => f.Random.Number(1, 3)) - .RuleFor(o => o.Item, f => f.Commerce.Product()); + action.Should().Throw(); + } - Order testOrder1 = orderFaker; - Order testOrder2 = orderFaker; - Order testOrder3 = orderFaker; + [Fact] + public void implicit_operator_test() + { + var orderFaker = new Faker() + .RuleFor(o => o.OrderId, f => f.IndexVariable++) + .RuleFor(o => o.Quantity, f => f.Random.Number(1, 3)) + .RuleFor(o => o.Item, f => f.Commerce.Product()); - testOrder1.Dump(); - testOrder2.Dump(); - testOrder3.Dump(); + Order testOrder1 = orderFaker; + Order testOrder2 = orderFaker; + Order testOrder3 = orderFaker; - var threeOrders = new[] {testOrder1, testOrder2, testOrder3}; - threeOrders.Select(o => o.Item).Should().ContainInOrder("Computer", "Tuna", "Soap"); - threeOrders.Select(o => o.Quantity).Should().ContainInOrder(2, 3, 1); + testOrder1.Dump(); + testOrder2.Dump(); + testOrder3.Dump(); - var testOrders = Enumerable.Range(1, 3) - .Select(x => (Order)orderFaker) - .ToArray(); + var threeOrders = new[] {testOrder1, testOrder2, testOrder3}; + threeOrders.Select(o => o.Item).Should().ContainInOrder("Computer", "Tuna", "Soap"); + threeOrders.Select(o => o.Quantity).Should().ContainInOrder(2, 3, 1); - testOrders.Dump(); + var testOrders = Enumerable.Range(1, 3) + .Select(x => (Order)orderFaker) + .ToArray(); - testOrders.Select(o => o.Item).Should().ContainInOrder("Chicken", "Gloves", "Mouse"); - testOrders.Select(o => o.Quantity).Should().ContainInOrder(1, 2, 3); - } + testOrders.Dump(); - [Fact] - public void can_clamp_string_length() - { - var c = new Company(); + testOrders.Select(o => o.Item).Should().ContainInOrder("Chicken", "Gloves", "Mouse"); + testOrders.Select(o => o.Quantity).Should().ContainInOrder(1, 2, 3); + } - var cnames = Enumerable.Range(1, 200).Select(i => c.CompanyName(0).ClampLength(12, 15)); + [Fact] + public void can_clamp_string_length() + { + var c = new Company(); - cnames.Any(name => name.EndsWith(" ")).Should().BeFalse(); - cnames.Dump(); - } + var cnames = Enumerable.Range(1, 200).Select(i => c.CompanyName(0).ClampLength(12, 15)); - public class Issue47 - { - public string Foo { get; set; } - public string Bar { get; set; } - public string Baz { get; set; } - public string Bake; - public string Make; - public string Fake; - } + cnames.Any(name => name.EndsWith(" ")).Should().BeFalse(); + cnames.Dump(); + } - public class Order - { - public int OrderId { get; set; } - public string Item { get; set; } - public int Quantity { get; set; } - public int? LotNumber { get; set; } - } + public class Issue47 + { + public string Foo { get; set; } + public string Bar { get; set; } + public string Baz { get; set; } + public string Bake; + public string Make; + public string Fake; + } - public enum Gender - { - Male, - Female - } + public class Order + { + public int OrderId { get; set; } + public string Item { get; set; } + public int Quantity { get; set; } + public int? LotNumber { get; set; } + } - public class User + public enum Gender + { + Male, + Female + } + + public class User + { + public User(int userId, string ssn) { - public User(int userId, string ssn) - { - this.Id = userId; - this.SSN = ssn; - } - - public int Id { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } - public string FullName { get; set; } - public string UserName { get; set; } - public string Email { get; set; } - public string SomethingUnique { get; set; } - public Guid SomeGuid { get; set; } - - public string Avatar { get; set; } - public Guid CartId { get; set; } - public string SSN { get; set; } - public Gender Gender { get; set; } - - public List Orders { get; set; } + this.Id = userId; + this.SSN = ssn; } - [Fact] - public void just_want_to_set_a_value() - { - var faker = new Faker() - .RuleFor(o => o.OrderId, 25) - .RuleFor(o => o.Item, "foo"); + public int Id { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } + public string FullName { get; set; } + public string UserName { get; set; } + public string Email { get; set; } + public string SomethingUnique { get; set; } + public Guid SomeGuid { get; set; } + + public string Avatar { get; set; } + public Guid CartId { get; set; } + public string SSN { get; set; } + public Gender Gender { get; set; } + + public List Orders { get; set; } + } - faker.Generate().OrderId.Should().Be(25); - faker.Generate().Item.Should().Be("foo"); - } + [Fact] + public void just_want_to_set_a_value() + { + var faker = new Faker() + .RuleFor(o => o.OrderId, 25) + .RuleFor(o => o.Item, "foo"); - [Fact] - public void create_rules_for_an_object_the_easy_way() - { - var faker = new Faker() - .Rules((f, o) => - { - o.Quantity = f.Random.Number(1, 4); - o.Item = f.Commerce.Product(); - o.OrderId = 25; - }); - - Order result = faker; - result.Dump(); - result.Item.Should().Be("Computer"); - result.OrderId.Should().Be(25); - result.Quantity.Should().BeInRange(1, 4); - } + faker.Generate().OrderId.Should().Be(25); + faker.Generate().Item.Should().Be("foo"); + } - [Fact] - public void can_create_rule_for_object_multiple_times() - { - var faker = new Faker() - .Rules((f, o) => - { - o.Quantity = f.Random.Number(1, 4); - o.Item = f.Commerce.Product(); - o.OrderId = 25; - }); - - var faker2 = faker.Rules((f, o) => { o.OrderId = 26; }); - - Order result = faker2; - result.OrderId.Should().Be(26); - result.Item.Should().Be("Computer"); - } + [Fact] + public void create_rules_for_an_object_the_easy_way() + { + var faker = new Faker() + .Rules((f, o) => + { + o.Quantity = f.Random.Number(1, 4); + o.Item = f.Commerce.Product(); + o.OrderId = 25; + }); + + Order result = faker; + result.Dump(); + result.Item.Should().Be("Computer"); + result.OrderId.Should().Be(25); + result.Quantity.Should().BeInRange(1, 4); + } - public enum Colors - { - Red, - Blue, - Green - } + [Fact] + public void can_create_rule_for_object_multiple_times() + { + var faker = new Faker() + .Rules((f, o) => + { + o.Quantity = f.Random.Number(1, 4); + o.Item = f.Commerce.Product(); + o.OrderId = 25; + }); - [Fact] - public void pick_random_exclude() - { - var faker = new Faker(); - var m = faker.PickRandomWithout(Colors.Red, Colors.Green); - m.Should().Be(Colors.Blue); - } + var faker2 = faker.Rules((f, o) => { o.OrderId = 26; }); - [Fact] - public void pick_a_random_enum_only_from_the_param_list() - { - var faker = new Faker(); - var f = faker.PickRandom(Colors.Red, Colors.Green); - f.Should().Be(Colors.Green); - } + Order result = faker2; + result.OrderId.Should().Be(26); + result.Item.Should().Be("Computer"); + } - [Fact] - public void can_pick_a_random_item_from_parameter_list() - { - var faker = new Faker(); - var pet = faker.PickRandom("cat", "dog", "fish"); - pet.Should().Be("dog"); - } + public enum Colors + { + Red, + Blue, + Green + } - [Fact] - public void can_pick_a_random_item_from_parameter_list2() - { - var faker = new Faker(); - var n = faker.PickRandomParam(1, 2, 3); - n.Should().Be(2); - } + [Fact] + public void pick_random_exclude() + { + var faker = new Faker(); + var m = faker.PickRandomWithout(Colors.Red, Colors.Green); + m.Should().Be(Colors.Blue); + } - [Fact] - public void can_pick_a_random_number_int32array() - { - var numbers = new[] {1, 2, 3}; - var faker = new Faker(); - var n = faker.PickRandom(numbers); - n.Should().BeOneOf(1, 2, 3); - } + [Fact] + public void pick_a_random_enum_only_from_the_param_list() + { + var faker = new Faker(); + var f = faker.PickRandom(Colors.Red, Colors.Green); + f.Should().Be(Colors.Green); + } - [Fact] - public void can_pick_random_item_of_linq_of_things() - { - var numbers = Enumerable.Range(1, 3).Select(i => i); - var faker = new Faker(); - var n = faker.PickRandom(numbers); - n.Should().BeOneOf(1, 2, 3); - } + [Fact] + public void can_pick_a_random_item_from_parameter_list() + { + var faker = new Faker(); + var pet = faker.PickRandom("cat", "dog", "fish"); + pet.Should().Be("dog"); + } - [Fact] - public void can_generate_forever() + [Fact] + public void can_pick_a_random_item_from_parameter_list2() + { + var faker = new Faker(); + var n = faker.PickRandomParam(1, 2, 3); + n.Should().Be(2); + } + + [Fact] + public void can_pick_a_random_number_int32array() + { + var numbers = new[] {1, 2, 3}; + var faker = new Faker(); + var n = faker.PickRandom(numbers); + n.Should().BeOneOf(1, 2, 3); + } + + [Fact] + public void can_pick_random_item_of_linq_of_things() + { + var numbers = Enumerable.Range(1, 3).Select(i => i); + var faker = new Faker(); + var n = faker.PickRandom(numbers); + n.Should().BeOneOf(1, 2, 3); + } + + [Fact] + public void can_generate_forever() + { + var orderFaker = new Faker() + .RuleFor(o => o.OrderId, f => f.IndexVariable++) + .RuleFor(o => o.Quantity, f => f.Random.Number(1, 3)) + .RuleFor(o => o.Item, f => f.Commerce.Product()); + + var source = orderFaker.GenerateForever(); + var count = 0; + foreach( var order in source ) { - var orderFaker = new Faker() - .RuleFor(o => o.OrderId, f => f.IndexVariable++) - .RuleFor(o => o.Quantity, f => f.Random.Number(1, 3)) - .RuleFor(o => o.Item, f => f.Commerce.Product()); - - var source = orderFaker.GenerateForever(); - var count = 0; - foreach( var order in source ) - { - order.Item.Should().NotBeNullOrWhiteSpace(); - order.Quantity.Should().BeInRange(1, 3); - order.OrderId.Should().BeGreaterOrEqualTo(0); - count++; - if( count > 99 ) break; - } + order.Item.Should().NotBeNullOrWhiteSpace(); + order.Quantity.Should().BeInRange(1, 3); + order.OrderId.Should().BeGreaterOrEqualTo(0); + count++; + if( count > 99 ) break; } } } diff --git a/Source/Bogus.Tests/GitHubIssues/Issue10.cs b/Source/Bogus.Tests/GitHubIssues/Issue10.cs index b03a5547..6d582f08 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue10.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue10.cs @@ -4,74 +4,73 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue10 : SeededTest { - public class Issue10 : SeededTest + public class Bar { - public class Bar - { - public int Id { get; set; } - public string Name; - public string Email { get; set; } - internal string LastName; - } - - [Fact] - public void issue_10_should_be_able_to_fake_fields() - { - var faker = new Faker() - .RuleFor(b => b.Email, f => f.Internet.Email()) - .RuleFor(b => b.Name, f => f.Name.FirstName()) - .RuleFor(b => b.LastName, f => f.Name.LastName()); - - var bar = faker.Generate(); - - bar.Dump(); - bar.Name.Should().NotBeNullOrEmpty(); - bar.Email.Length.Should().BeGreaterOrEqualTo(2); - bar.Email.Should().NotBeNullOrEmpty(); - bar.Email.Length.Should().BeGreaterOrEqualTo(2); + public int Id { get; set; } + public string Name; + public string Email { get; set; } + internal string LastName; + } - bar.LastName.Should().NotBeNullOrEmpty(); - bar.LastName.Length.Should().BeGreaterOrEqualTo(2); - } + [Fact] + public void issue_10_should_be_able_to_fake_fields() + { + var faker = new Faker() + .RuleFor(b => b.Email, f => f.Internet.Email()) + .RuleFor(b => b.Name, f => f.Name.FirstName()) + .RuleFor(b => b.LastName, f => f.Name.LastName()); + var bar = faker.Generate(); - [Fact] - public void issue_12_bogus_should_be_thread_safe() - { - int threadCount = 20; + bar.Dump(); + bar.Name.Should().NotBeNullOrEmpty(); + bar.Email.Length.Should().BeGreaterOrEqualTo(2); + bar.Email.Should().NotBeNullOrEmpty(); + bar.Email.Length.Should().BeGreaterOrEqualTo(2); - var barId = 0; - var faker = new Faker() - .RuleFor(b => b.Id, f => barId++) - .RuleFor(b => b.Email, f => f.Internet.Email()) - .RuleFor(b => b.Name, f => f.Name.FirstName()) - .RuleFor(b => b.LastName, f => f.Name.LastName()); + bar.LastName.Should().NotBeNullOrEmpty(); + bar.LastName.Length.Should().BeGreaterOrEqualTo(2); + } - var threads = new List(); - for( var x = 0; x < threadCount; x++ ) - { - var thread = Task.Run(() => - { - var fakes = faker.Generate(3); - fakes.Dump(); - }); - threads.Add(thread); - } - Task.WaitAll(threads.ToArray()); + [Fact] + public void issue_12_bogus_should_be_thread_safe() + { + int threadCount = 20; - Console.WriteLine(barId); - barId.Should().Be(60); + var barId = 0; + var faker = new Faker() + .RuleFor(b => b.Id, f => barId++) + .RuleFor(b => b.Email, f => f.Internet.Email()) + .RuleFor(b => b.Name, f => f.Name.FirstName()) + .RuleFor(b => b.LastName, f => f.Name.LastName()); - var result = Parallel.For(0, threadCount, i => + var threads = new List(); + for( var x = 0; x < threadCount; x++ ) + { + var thread = Task.Run(() => { var fakes = faker.Generate(3); + fakes.Dump(); }); - - Console.WriteLine(barId); - barId.Should().Be(120); + threads.Add(thread); } + + Task.WaitAll(threads.ToArray()); + + Console.WriteLine(barId); + barId.Should().Be(60); + + var result = Parallel.For(0, threadCount, i => + { + var fakes = faker.Generate(3); + }); + + Console.WriteLine(barId); + barId.Should().Be(120); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue100.cs b/Source/Bogus.Tests/GitHubIssues/Issue100.cs index 09a86e7b..e4902206 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue100.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue100.cs @@ -5,204 +5,203 @@ using Xunit; using Xunit.Abstractions; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue100 : SeededTest { - public class Issue100 : SeededTest - { - private readonly ITestOutputHelper console; + private readonly ITestOutputHelper console; - public Issue100(ITestOutputHelper console) - { - this.console = console; - } + public Issue100(ITestOutputHelper console) + { + this.console = console; + } - [Fact] - public void dataset_test() - { - var c = new Commerce - { - Random = new Randomizer(54321) - }; + [Fact] + public void dataset_test() + { + var c = new Commerce + { + Random = new Randomizer(54321) + }; - c.Product().Should().Be("Shirt"); - Randomizer.Seed = new Random(7331); - c.Product().Should().Be("Soap"); + c.Product().Should().Be("Shirt"); + Randomizer.Seed = new Random(7331); + c.Product().Should().Be("Soap"); - Randomizer.Seed = new Random(1337); - c.Random = new Randomizer(54321); + Randomizer.Seed = new Random(1337); + c.Random = new Randomizer(54321); - c.Product().Should().Be("Shirt"); - Randomizer.Seed = new Random(3173); - c.Product().Should().Be("Soap"); - } + c.Product().Should().Be("Shirt"); + Randomizer.Seed = new Random(3173); + c.Product().Should().Be("Soap"); + } - [Fact] - public void faker_test() - { - var f = new Faker - { - Random = new Randomizer(54321) - }; + [Fact] + public void faker_test() + { + var f = new Faker + { + Random = new Randomizer(54321) + }; - f.Commerce.Product().Should().Be("Shirt"); - Randomizer.Seed = new Random(7331); - f.Commerce.Product().Should().Be("Soap"); + f.Commerce.Product().Should().Be("Shirt"); + Randomizer.Seed = new Random(7331); + f.Commerce.Product().Should().Be("Soap"); - Randomizer.Seed = new Random(1337); - f.Random = new Randomizer(54321); + Randomizer.Seed = new Random(1337); + f.Random = new Randomizer(54321); - f.Commerce.Product().Should().Be("Shirt"); - Randomizer.Seed = new Random(3173); - f.Commerce.Product().Should().Be("Soap"); - } + f.Commerce.Product().Should().Be("Shirt"); + Randomizer.Seed = new Random(3173); + f.Commerce.Product().Should().Be("Soap"); + } - [Fact] - public void randomizer_twice() - { - var r = new Randomizer(88); - Enumerable.Range(1, 4) - .Select(i => r.Number(1, 3)) - .Should().Equal(3, 2, 1, 2); - - r = new Randomizer(88); - Enumerable.Range(1, 4) - .Select(i => r.Number(1, 3)) - .Should().Equal(3, 2, 1, 2); - } + [Fact] + public void randomizer_twice() + { + var r = new Randomizer(88); + Enumerable.Range(1, 4) + .Select(i => r.Number(1, 3)) + .Should().Equal(3, 2, 1, 2); + + r = new Randomizer(88); + Enumerable.Range(1, 4) + .Select(i => r.Number(1, 3)) + .Should().Equal(3, 2, 1, 2); + } - [Fact] - public void faker_test_2() - { - var f = new Faker(); - f.Random = new Randomizer(88); + [Fact] + public void faker_test_2() + { + var f = new Faker(); + f.Random = new Randomizer(88); - Enumerable.Range(1, 4) - .Select(i => f.Random.Number(1, 3)) - .Should().Equal(3, 2, 1, 2); + Enumerable.Range(1, 4) + .Select(i => f.Random.Number(1, 3)) + .Should().Equal(3, 2, 1, 2); - f.Random = new Randomizer(88); + f.Random = new Randomizer(88); - Enumerable.Range(1, 4) - .Select(i => f.Random.Number(1, 3)) - .Should().Equal(3, 2, 1, 2); - } + Enumerable.Range(1, 4) + .Select(i => f.Random.Number(1, 3)) + .Should().Equal(3, 2, 1, 2); + } - [Fact] - public void simple_faker_t_test() - { - var orderFaker = new Faker() - .UseSeed(88) - .RuleFor(o => o.Quantity, f => { return f.Random.Number(1, 3); }); + [Fact] + public void simple_faker_t_test() + { + var orderFaker = new Faker() + .UseSeed(88) + .RuleFor(o => o.Quantity, f => { return f.Random.Number(1, 3); }); - var order = orderFaker.Generate(); + var order = orderFaker.Generate(); - order.Quantity.Should().Be(3); + order.Quantity.Should().Be(3); - orderFaker.UseSeed(88); + orderFaker.UseSeed(88); - order = orderFaker.Generate(); + order = orderFaker.Generate(); - order.Quantity.Should().Be(3); - } + order.Quantity.Should().Be(3); + } - [Fact] - public void complex_faker_t_test() - { - Randomizer.Seed = new Random(7331); + [Fact] + public void complex_faker_t_test() + { + Randomizer.Seed = new Random(7331); - var orderFaker = new Faker() - .UseSeed(88) - .RuleFor(o => o.OrderId, f => f.IndexVariable++) - .RuleFor(o => o.Quantity, f => f.Random.Number(1, 3)) - .RuleFor(o => o.Item, f => f.Commerce.Product()); + var orderFaker = new Faker() + .UseSeed(88) + .RuleFor(o => o.OrderId, f => f.IndexVariable++) + .RuleFor(o => o.Quantity, f => f.Random.Number(1, 3)) + .RuleFor(o => o.Item, f => f.Commerce.Product()); - var items = Enumerable.Range(1, 4) - .Select(i => orderFaker.Generate()) - .ToArray(); + var items = Enumerable.Range(1, 4) + .Select(i => orderFaker.Generate()) + .ToArray(); - console.WriteLine(items.DumpString()); + console.WriteLine(items.DumpString()); - items.Select(i => i.OrderId).Should().Equal(0, 1, 2, 3); + items.Select(i => i.OrderId).Should().Equal(0, 1, 2, 3); - CheckSequence(items); + CheckSequence(items); - //using the same seed again should - //reset the state. - orderFaker.UseSeed(88); - //and it should override a set seeded test - Randomizer.Seed = new Random(1337); + //using the same seed again should + //reset the state. + orderFaker.UseSeed(88); + //and it should override a set seeded test + Randomizer.Seed = new Random(1337); - items = Enumerable.Range(1, 4) - .Select(i => orderFaker.Generate()) - .ToArray(); + items = Enumerable.Range(1, 4) + .Select(i => orderFaker.Generate()) + .ToArray(); - items.Select(i => i.OrderId).Should().Equal(4, 5, 6, 7); + items.Select(i => i.OrderId).Should().Equal(4, 5, 6, 7); - console.WriteLine(items.DumpString()); + console.WriteLine(items.DumpString()); - CheckSequence(items); - } + CheckSequence(items); + } - [Fact] - public void sequence_generate_list_of_4_vs_generate_4_times_should_produce_same_content() - { - Randomizer.Seed = new Random(7331); - - var orderFaker = new Faker() - .UseSeed(88) - .RuleFor(o => o.OrderId, f => f.IndexVariable++) - .RuleFor(o => o.Quantity, f => f.Random.Number(1, 3)) - .RuleFor(o => o.Item, f => f.Commerce.Product()); - - var batch = orderFaker.Generate(4).ToArray(); - batch.Select(i => i.OrderId).Should().Equal(0, 1, 2, 3); - CheckSequence(batch); - - var sequence = new Examples.Order[4]; - - //reset - Randomizer.Seed = new Random(7331); - orderFaker.UseSeed(88); - - sequence[0] = orderFaker.Generate(); - sequence[1] = orderFaker.Generate(); - sequence[2] = orderFaker.Generate(); - sequence[3] = orderFaker.Generate(); - - sequence.Select(i => i.OrderId).Should().Equal(4, 5, 6, 7); - - CheckSequence(sequence); - } + [Fact] + public void sequence_generate_list_of_4_vs_generate_4_times_should_produce_same_content() + { + Randomizer.Seed = new Random(7331); + + var orderFaker = new Faker() + .UseSeed(88) + .RuleFor(o => o.OrderId, f => f.IndexVariable++) + .RuleFor(o => o.Quantity, f => f.Random.Number(1, 3)) + .RuleFor(o => o.Item, f => f.Commerce.Product()); + + var batch = orderFaker.Generate(4).ToArray(); + batch.Select(i => i.OrderId).Should().Equal(0, 1, 2, 3); + CheckSequence(batch); + + var sequence = new Examples.Order[4]; + + //reset + Randomizer.Seed = new Random(7331); + orderFaker.UseSeed(88); + + sequence[0] = orderFaker.Generate(); + sequence[1] = orderFaker.Generate(); + sequence[2] = orderFaker.Generate(); + sequence[3] = orderFaker.Generate(); + + sequence.Select(i => i.OrderId).Should().Equal(4, 5, 6, 7); + + CheckSequence(sequence); + } - [Fact] - public void parallel_determinism() + [Fact] + public void parallel_determinism() + { + var orderFaker = new Faker() + .RuleFor(o => o.OrderId, f => f.IndexVariable++) + .RuleFor(o => o.Quantity, f => f.Random.Number(1, 3)) + .RuleFor(o => o.Item, f => f.Commerce.Product()); + + var orders = ParallelEnumerable.Range(1, 5) + .Select(threadId => + orderFaker + .Clone() + .UseSeed(88) + .Generate(4).ToArray() + ).ToArray(); + + foreach( var orderOfFour in orders ) { - var orderFaker = new Faker() - .RuleFor(o => o.OrderId, f => f.IndexVariable++) - .RuleFor(o => o.Quantity, f => f.Random.Number(1, 3)) - .RuleFor(o => o.Item, f => f.Commerce.Product()); - - var orders = ParallelEnumerable.Range(1, 5) - .Select(threadId => - orderFaker - .Clone() - .UseSeed(88) - .Generate(4).ToArray() - ).ToArray(); - - foreach( var orderOfFour in orders ) - { - CheckSequence(orderOfFour); - } + CheckSequence(orderOfFour); } + } - private void CheckSequence(Examples.Order[] items) - { - items.Select(i => i.Item) - .Should().Equal("Tuna", "Pants", "Shoes", "Soap"); + private void CheckSequence(Examples.Order[] items) + { + items.Select(i => i.Item) + .Should().Equal("Tuna", "Pants", "Shoes", "Soap"); - items.Select(i => i.Quantity) - .Should().Equal(3, 1, 3, 2); - } + items.Select(i => i.Quantity) + .Should().Equal(3, 1, 3, 2); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue102.cs b/Source/Bogus.Tests/GitHubIssues/Issue102.cs index 3890f343..5b577b56 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue102.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue102.cs @@ -1,33 +1,32 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue102 : SeededTest { - public class Issue102 : SeededTest + [Fact] + public void deterministic_uuid_using_global_seed() { - [Fact] - public void deterministic_uuid_using_global_seed() - { - var r = new Randomizer(); - r.Uuid().Should().Be("{4c9c23da-c4e0-d72d-e3c4-a89617f255b2}"); - ResetGlobalSeed(); //should have an effect only if a new randomizer is created - r.Uuid().Should().Be("{bd59c865-cda5-44f4-a28e-db17c014d586}"); + var r = new Randomizer(); + r.Uuid().Should().Be("{4c9c23da-c4e0-d72d-e3c4-a89617f255b2}"); + ResetGlobalSeed(); //should have an effect only if a new randomizer is created + r.Uuid().Should().Be("{bd59c865-cda5-44f4-a28e-db17c014d586}"); - r = new Randomizer(); - r.Uuid().Should().Be("{4c9c23da-c4e0-d72d-e3c4-a89617f255b2}"); - } + r = new Randomizer(); + r.Uuid().Should().Be("{4c9c23da-c4e0-d72d-e3c4-a89617f255b2}"); + } - [Fact] - public void deterministic_uuid_using_local_seed() - { - var r = new Randomizer(1337); - r.Uuid().Should().Be("{c7f40068-5e43-aa02-c27c-4fd927fc2227}"); - ResetGlobalSeed(); //should have no effect - r.Uuid().Should().Be("{b254896a-12e5-1eef-9af7-227ef036e328}"); + [Fact] + public void deterministic_uuid_using_local_seed() + { + var r = new Randomizer(1337); + r.Uuid().Should().Be("{c7f40068-5e43-aa02-c27c-4fd927fc2227}"); + ResetGlobalSeed(); //should have no effect + r.Uuid().Should().Be("{b254896a-12e5-1eef-9af7-227ef036e328}"); - ResetGlobalSeed(); //should have no effect - r = new Randomizer(1337); - r.Uuid().Should().Be("{c7f40068-5e43-aa02-c27c-4fd927fc2227}"); - } + ResetGlobalSeed(); //should have no effect + r = new Randomizer(1337); + r.Uuid().Should().Be("{c7f40068-5e43-aa02-c27c-4fd927fc2227}"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue104.cs b/Source/Bogus.Tests/GitHubIssues/Issue104.cs index 990796e2..ccc63adc 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue104.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue104.cs @@ -5,103 +5,102 @@ using Xunit; using Xunit.Abstractions; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue104 : SeededTest { - public class Issue104 : SeededTest + private readonly ITestOutputHelper console; + + public Issue104(ITestOutputHelper console) + { + this.console = console; + } + + public class Order2 : Order { - private readonly ITestOutputHelper console; - - public Issue104(ITestOutputHelper console) - { - this.console = console; - } - - public class Order2 : Order - { - public int Tax { get; set; } - } - - [Fact] - public void without_derived_faker() - { - var rootSeed = 0; - var faker1 = new Faker() - .UseSeed(rootSeed++) - .RuleFor(o => o.OrderId, f => f.IndexVariable++) - .RuleFor(o => o.Item, f => f.Commerce.Product()) - .RuleFor(o => o.Quantity, f => f.Random.Int(1, 5)); - - faker1.FinishWith((f, o) => - { - faker1.UseSeed(rootSeed++); - }); - - - var orders1 = faker1.Generate(3); - console.Dump(orders1); - CheckSequence(orders1); - - - rootSeed = 0; - var faker2 = new Faker() - .UseSeed(rootSeed++) - .RuleFor(o => o.OrderId, f => f.IndexVariable++) - .RuleFor(o => o.Item, f => f.Commerce.Product()) - .RuleFor(o => o.Quantity, f => f.Random.Int(1, 5)) - .RuleFor(o => o.Tax, f=> f.Random.Int(9, 15) ); - - faker2.FinishWith((f, o) => - { - faker2.UseSeed(rootSeed++); - }); - - var orders2 = faker2.Generate(3); - - CheckSequence(orders2); - - console.Dump(orders2); - } - - [Fact] - public void adding_new_property_should_not_change_subsequent_items() - { - var faker1 = new CustomFaker() - .RuleFor(o => o.OrderId, f => f.IndexVariable++) - .RuleFor(o => o.Item, f => f.Commerce.Product()) - .RuleFor(o => o.Quantity, f => f.Random.Int(1, 5)); - - var orders1 = faker1.Generate(3); - console.Dump(orders1); - CheckSequence(orders1); - - var faker2 = new CustomFaker() - .RuleFor(o => o.OrderId, f => f.IndexVariable++) - .RuleFor(o => o.Item, f => f.Commerce.Product()) - .RuleFor(o => o.Quantity, f => f.Random.Int(1, 5)) - .RuleFor(o => o.Tax, f => f.Random.Int(9, 15)); - - var orders2 = faker2.Generate(3); - console.Dump(orders2); - CheckSequence(orders2); - } - - - void CheckSequence(IEnumerable orders) - { - orders.Select(o => o.OrderId).Should().Equal(0, 1, 2); - orders.Select(o => o.Item).Should().Equal("Fish", "Bike", "Cheese"); - orders.Select(o => o.Quantity).Should().Equal(5, 1, 3); - } + public int Tax { get; set; } + } + + [Fact] + public void without_derived_faker() + { + var rootSeed = 0; + var faker1 = new Faker() + .UseSeed(rootSeed++) + .RuleFor(o => o.OrderId, f => f.IndexVariable++) + .RuleFor(o => o.Item, f => f.Commerce.Product()) + .RuleFor(o => o.Quantity, f => f.Random.Int(1, 5)); + + faker1.FinishWith((f, o) => + { + faker1.UseSeed(rootSeed++); + }); + + + var orders1 = faker1.Generate(3); + console.Dump(orders1); + CheckSequence(orders1); + + rootSeed = 0; + var faker2 = new Faker() + .UseSeed(rootSeed++) + .RuleFor(o => o.OrderId, f => f.IndexVariable++) + .RuleFor(o => o.Item, f => f.Commerce.Product()) + .RuleFor(o => o.Quantity, f => f.Random.Int(1, 5)) + .RuleFor(o => o.Tax, f=> f.Random.Int(9, 15) ); + + faker2.FinishWith((f, o) => + { + faker2.UseSeed(rootSeed++); + }); + + var orders2 = faker2.Generate(3); + + CheckSequence(orders2); + + console.Dump(orders2); + } + + [Fact] + public void adding_new_property_should_not_change_subsequent_items() + { + var faker1 = new CustomFaker() + .RuleFor(o => o.OrderId, f => f.IndexVariable++) + .RuleFor(o => o.Item, f => f.Commerce.Product()) + .RuleFor(o => o.Quantity, f => f.Random.Int(1, 5)); + + var orders1 = faker1.Generate(3); + console.Dump(orders1); + CheckSequence(orders1); + + var faker2 = new CustomFaker() + .RuleFor(o => o.OrderId, f => f.IndexVariable++) + .RuleFor(o => o.Item, f => f.Commerce.Product()) + .RuleFor(o => o.Quantity, f => f.Random.Int(1, 5)) + .RuleFor(o => o.Tax, f => f.Random.Int(9, 15)); + + var orders2 = faker2.Generate(3); + console.Dump(orders2); + CheckSequence(orders2); } - public class CustomFaker : Faker where T : class + + void CheckSequence(IEnumerable orders) + { + orders.Select(o => o.OrderId).Should().Equal(0, 1, 2); + orders.Select(o => o.Item).Should().Equal("Fish", "Bike", "Cheese"); + orders.Select(o => o.Quantity).Should().Equal(5, 1, 3); + } + +} + +public class CustomFaker : Faker where T : class +{ + private int seed; + protected override void PopulateInternal(T instance, string[] ruleSets) { - private int seed; - protected override void PopulateInternal(T instance, string[] ruleSets) - { - this.UseSeed(seed++); - base.PopulateInternal(instance, ruleSets); - } + this.UseSeed(seed++); + base.PopulateInternal(instance, ruleSets); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue114.cs b/Source/Bogus.Tests/GitHubIssues/Issue114.cs index 56ab353a..3479cec4 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue114.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue114.cs @@ -3,22 +3,21 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue114 : SeededTest { - public class Issue114 : SeededTest + [Fact] + public void should_be_able_to_get_an_obfuscated_credit_card_number() + { + var finance = new Finance(); + finance.CreditCardNumberObfuscated().Should().Be("****-****-****-6186"); + } + + [Fact] + public void cn_get_last_for_credit_card_digits() { - [Fact] - public void should_be_able_to_get_an_obfuscated_credit_card_number() - { - var finance = new Finance(); - finance.CreditCardNumberObfuscated().Should().Be("****-****-****-6186"); - } - - [Fact] - public void cn_get_last_for_credit_card_digits() - { - var finance = new Finance(); - finance.CreditCardNumberLastFourDigits().Should().Be("6186"); - } + var finance = new Finance(); + finance.CreditCardNumberLastFourDigits().Should().Be("6186"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue115.cs b/Source/Bogus.Tests/GitHubIssues/Issue115.cs index ec7f77b2..9e050cfd 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue115.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue115.cs @@ -4,62 +4,61 @@ using Xunit; using Xunit.Abstractions; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue115 : SeededTest { - public class Issue115 : SeededTest - { - private readonly ITestOutputHelper console; + private readonly ITestOutputHelper console; - public Issue115(ITestOutputHelper console) - { - this.console = console; - } + public Issue115(ITestOutputHelper console) + { + this.console = console; + } - public class Customer - { - public string Name { get; set; } - public int OrderId { get; set; } - public Order Order { get; set; } - } - - [Fact] - public void should_throw_with_nested_expression() - { - Action fakerMaker = () => new Faker() - .RuleFor(o => o.Order.Item, f => f.Random.Int(1, 1000).ToString()); + public class Customer + { + public string Name { get; set; } + public int OrderId { get; set; } + public Order Order { get; set; } + } + + [Fact] + public void should_throw_with_nested_expression() + { + Action fakerMaker = () => new Faker() + .RuleFor(o => o.Order.Item, f => f.Random.Int(1, 1000).ToString()); - fakerMaker.Should().Throw(); + fakerMaker.Should().Throw(); - } + } - [Fact] - public void calling_finish_with_twice_is_okay() - { - var productCalled = false; - var colorCalled = false; + [Fact] + public void calling_finish_with_twice_is_okay() + { + var productCalled = false; + var colorCalled = false; - var faker = new Faker() - .RuleFor(o => o.OrderId, f => f.Random.Number(1,50)) - .FinishWith((f, o) => - { - productCalled = true; - o.Item = f.Commerce.Product(); - }) - .FinishWith((f, o) => - { - colorCalled = true; - o.Item = f.Commerce.Color(); - }); + var faker = new Faker() + .RuleFor(o => o.OrderId, f => f.Random.Number(1,50)) + .FinishWith((f, o) => + { + productCalled = true; + o.Item = f.Commerce.Product(); + }) + .FinishWith((f, o) => + { + colorCalled = true; + o.Item = f.Commerce.Color(); + }); - var order = faker.Generate(); + var order = faker.Generate(); - order.Item.Should().Be("yellow"); - - //sanity check - productCalled.Should().BeFalse(); - colorCalled.Should().BeTrue(); + order.Item.Should().Be("yellow"); + + //sanity check + productCalled.Should().BeFalse(); + colorCalled.Should().BeTrue(); - console.Dump(order); - } + console.Dump(order); } } diff --git a/Source/Bogus.Tests/GitHubIssues/Issue121.cs b/Source/Bogus.Tests/GitHubIssues/Issue121.cs index 029eff3d..a79befa9 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue121.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue121.cs @@ -3,81 +3,80 @@ using Xunit; using Xunit.Abstractions; -namespace Bogus.Tests.GitHubIssues -{ - public class Issue121 : SeededTest - { - private readonly ITestOutputHelper console; +namespace Bogus.Tests.GitHubIssues; - public Issue121(ITestOutputHelper console) - { - this.console = console; - } - public class TestObject - { - public Guid Id { get; set; } - public string Name { get; set; } - } +public class Issue121 : SeededTest +{ + private readonly ITestOutputHelper console; - [Fact(Skip = "Their example")] - public void Test() - { - var faker = new Faker() - .StrictMode(true) - .RuleFor(x => x.Id, Guid.NewGuid) - .RuleFor(x => x.Name, x => x.Person.FirstName) - .RuleSet("update", f => f.Ignore(x => x.Id)); + public Issue121(ITestOutputHelper console) + { + this.console = console; + } + public class TestObject + { + public Guid Id { get; set; } + public string Name { get; set; } + } - var obj = faker.Generate(); + [Fact(Skip = "Their example")] + public void Test() + { + var faker = new Faker() + .StrictMode(true) + .RuleFor(x => x.Id, Guid.NewGuid) + .RuleFor(x => x.Name, x => x.Person.FirstName) + .RuleSet("update", f => f.Ignore(x => x.Id)); - var id = obj.Id; // value copy - var name = obj.Name; // value copy + var obj = faker.Generate(); - faker.Populate(obj, "default,update"); + var id = obj.Id; // value copy + var name = obj.Name; // value copy - Assert.True(id == obj.Id); // fails - Assert.False(name == obj.Name); - } + faker.Populate(obj, "default,update"); - [Fact] - public void github_issue121_workaround() - { - var faker = new Faker() - .StrictMode(true) - .RuleFor(x => x.Id, x => Guid.NewGuid()) - .RuleFor(x => x.Name, x => x.Person.FirstName); + Assert.True(id == obj.Id); // fails + Assert.False(name == obj.Name); + } - var updateFaker = faker.Clone() - .Ignore(x => x.Id); + [Fact] + public void github_issue121_workaround() + { + var faker = new Faker() + .StrictMode(true) + .RuleFor(x => x.Id, x => Guid.NewGuid()) + .RuleFor(x => x.Name, x => x.Person.FirstName); - var obj = faker.Generate(); + var updateFaker = faker.Clone() + .Ignore(x => x.Id); - var id = obj.Id; // value copy - var name = obj.Name; // value copy + var obj = faker.Generate(); - updateFaker.Populate(obj); + var id = obj.Id; // value copy + var name = obj.Name; // value copy - console.Dump($"Copy values - id: {id}, name: {name}"); - console.Dump(obj); + updateFaker.Populate(obj); - id.Should().Be(obj.Id); - name.Should().NotBe(obj.Name); - } + console.Dump($"Copy values - id: {id}, name: {name}"); + console.Dump(obj); - [Fact] - public void last_call_ignoring_a_prop_should_be_ignored() - { - var faker = new Faker() - .RuleFor(x => x.Name, x => x.Person.FirstName) - .Ignore(x => x.Name); + id.Should().Be(obj.Id); + name.Should().NotBe(obj.Name); + } - //who wins? last call to ignore should win. + [Fact] + public void last_call_ignoring_a_prop_should_be_ignored() + { + var faker = new Faker() + .RuleFor(x => x.Name, x => x.Person.FirstName) + .Ignore(x => x.Name); - var obj = faker.Generate(); + //who wins? last call to ignore should win. - obj.Id.Should().BeEmpty(); - obj.Name.Should().BeNull(); - } + var obj = faker.Generate(); + obj.Id.Should().BeEmpty(); + obj.Name.Should().BeNull(); } + } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue124.cs b/Source/Bogus.Tests/GitHubIssues/Issue124.cs index 132a3476..9ae12154 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue124.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue124.cs @@ -6,191 +6,190 @@ using Bogus.Extensions; using Z.ExtensionMethods.ObjectExtensions; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue124 : SeededTest { - public class Issue124 : SeededTest + private readonly ITestOutputHelper console; + + public Issue124(ITestOutputHelper console) + { + this.console = console; + } + + [Fact] + public void test_nullable() + { + var faker = new Faker() + .RuleFor(p => p.Guid, f => f.Random.NullableUuid()) + .RuleFor(p => p.Name, f => f.Person.FullName); + + var fakes = faker.Generate(10); + + fakes.Should() + .Contain(p => p.Guid == null) + .And + .Contain(p => p.Guid != null); + } + + [Fact] + public void test_nullable_struct() { - private readonly ITestOutputHelper console; - - public Issue124(ITestOutputHelper console) - { - this.console = console; - } - - [Fact] - public void test_nullable() - { - var faker = new Faker() - .RuleFor(p => p.Guid, f => f.Random.NullableUuid()) - .RuleFor(p => p.Name, f => f.Person.FullName); - - var fakes = faker.Generate(10); - - fakes.Should() - .Contain(p => p.Guid == null) - .And - .Contain(p => p.Guid != null); - } - - [Fact] - public void test_nullable_struct() - { - var faker = new Faker() - .RuleFor(p => p.Guid, f => f.Random.Uuid().OrNull(f)) - .RuleFor(p => p.Name, f => f.Person.FullName); - - var fakes = faker.Generate(10); - - console.Dump(fakes); - - fakes.Should() - .Contain(p => p.Guid == null) - .And - .Contain(p => p.Guid != null); - } - - [Fact] - public void test_null_reference_type() - { - var faker = new Faker() - .RuleFor(x => x.Id, f => f.Random.Uuid()) - .RuleFor(x => x.Bar, f => new object().OrNull(f)); - - var fakes = faker.Generate(10); - - console.Dump(fakes); - - fakes.Should() - .Contain(f => f.Bar == null) - .And - .Contain(f => f.Bar != null); - } - - [Fact] - public void test_null_reference_type_between_fakers() - { - var personFaker = new Faker() - .RuleFor(p => p.Guid, f => f.Random.Uuid().OrNull(f)) - .RuleFor(p => p.Name, f => f.Person.FullName); - - var barFaker = new Faker() - .RuleFor(x => x.Id, f => f.Random.Uuid()) - .RuleFor(x => x.Person, f => personFaker.Generate().OrNull(f) ); - - var fakes = barFaker.Generate(20); - console.Dump(fakes); - - fakes.Should() - .Contain(f => f.Person == null) - .And - .Contain(f => f.Person != null) - .And - .Contain(f => f.Person != null && f.Person.Guid == null) - .And - .Contain(f => f.Person != null && f.Person.Guid != null); - } - - [Fact] - public void test_deterministic_or_null() - { - var faker = new Faker() - .RuleFor(x => x.Id, f => f.Random.Uuid()) - .RuleFor(x => x.Bar, f => new object().OrNull(f)); - - var fakes = faker.Generate(10); - - console.Dump(fakes); - - var bars = fakes.Select(f => f.Bar).ToArray(); - - var notNullObjects = bars.Where(b => b != null).ToArray(); - - bars.Should() - .ContainInOrder( - notNullObjects[0], - null, - null, - notNullObjects[1], - null, - notNullObjects[2], - notNullObjects[3], - null, - null, - notNullObjects[4] - ); - } - - [Fact] - public void nullable_int_and_nullable_reference_type() - { - var faker = new Faker() - .RuleFor(x => x.Id, f => f.Random.Int().OrNull(f)) - .RuleFor(x => x.Gud, f => f.Random.Guid().OrNull(f, .8f)) - .RuleFor(x => x.Obj, f => new object().OrNull(f)) - .RuleFor(x => x.Str, f => f.Random.Word().OrNull(f)); - - var q = faker.Generate(5); - - console.Dump(q); - - q[0].Id.Should().NotBeNull(); - q[0].Gud.Should().NotBeNull(); - q[0].Obj.Should().NotBeNull(); - q[0].Str.Should().NotBeNull(); - - q[1].Id.Should().NotBeNull(); - q[1].Gud.Should().NotBeNull(); - q[1].Obj.Should().NotBeNull(); - q[1].Str.Should().BeNull(); - - q[2].Id.Should().BeNull(); - q[2].Gud.Should().BeNull(); - q[2].Obj.Should().NotBeNull(); - q[2].Str.Should().NotBeNull(); - - q[3].Id.Should().BeNull(); - q[3].Gud.Should().NotBeNull(); - q[3].Obj.Should().BeNull(); - q[3].Str.Should().NotBeNull(); - - q[4].Id.Should().BeNull(); - q[4].Gud.Should().NotBeNull(); - q[4].Obj.Should().NotBeNull(); - q[4].Str.Should().BeNull(); - } - - public class Foo - { - public Guid Id { get; set; } - public object Bar { get; set; } - } - - public class Bar - { - public Guid Id { get; set; } - public Person Person { get; set; } - } - - public class Qux - { - public int? Id { get; set; } - public Guid? Gud { get; set; } - public object Obj { get; set; } - public string Str { get; set; } - } + var faker = new Faker() + .RuleFor(p => p.Guid, f => f.Random.Uuid().OrNull(f)) + .RuleFor(p => p.Name, f => f.Person.FullName); + + var fakes = faker.Generate(10); + + console.Dump(fakes); + + fakes.Should() + .Contain(p => p.Guid == null) + .And + .Contain(p => p.Guid != null); + } + + [Fact] + public void test_null_reference_type() + { + var faker = new Faker() + .RuleFor(x => x.Id, f => f.Random.Uuid()) + .RuleFor(x => x.Bar, f => new object().OrNull(f)); + + var fakes = faker.Generate(10); + + console.Dump(fakes); + + fakes.Should() + .Contain(f => f.Bar == null) + .And + .Contain(f => f.Bar != null); } - public class Person + [Fact] + public void test_null_reference_type_between_fakers() { - public Guid? Guid { get; set; } - public string Name { get; set; } + var personFaker = new Faker() + .RuleFor(p => p.Guid, f => f.Random.Uuid().OrNull(f)) + .RuleFor(p => p.Name, f => f.Person.FullName); + + var barFaker = new Faker() + .RuleFor(x => x.Id, f => f.Random.Uuid()) + .RuleFor(x => x.Person, f => personFaker.Generate().OrNull(f) ); + + var fakes = barFaker.Generate(20); + console.Dump(fakes); + + fakes.Should() + .Contain(f => f.Person == null) + .And + .Contain(f => f.Person != null) + .And + .Contain(f => f.Person != null && f.Person.Guid == null) + .And + .Contain(f => f.Person != null && f.Person.Guid != null); } - public static class ObjectExtensions + [Fact] + public void test_deterministic_or_null() + { + var faker = new Faker() + .RuleFor(x => x.Id, f => f.Random.Uuid()) + .RuleFor(x => x.Bar, f => new object().OrNull(f)); + + var fakes = faker.Generate(10); + + console.Dump(fakes); + + var bars = fakes.Select(f => f.Bar).ToArray(); + + var notNullObjects = bars.Where(b => b != null).ToArray(); + + bars.Should() + .ContainInOrder( + notNullObjects[0], + null, + null, + notNullObjects[1], + null, + notNullObjects[2], + notNullObjects[3], + null, + null, + notNullObjects[4] + ); + } + + [Fact] + public void nullable_int_and_nullable_reference_type() + { + var faker = new Faker() + .RuleFor(x => x.Id, f => f.Random.Int().OrNull(f)) + .RuleFor(x => x.Gud, f => f.Random.Guid().OrNull(f, .8f)) + .RuleFor(x => x.Obj, f => new object().OrNull(f)) + .RuleFor(x => x.Str, f => f.Random.Word().OrNull(f)); + + var q = faker.Generate(5); + + console.Dump(q); + + q[0].Id.Should().NotBeNull(); + q[0].Gud.Should().NotBeNull(); + q[0].Obj.Should().NotBeNull(); + q[0].Str.Should().NotBeNull(); + + q[1].Id.Should().NotBeNull(); + q[1].Gud.Should().NotBeNull(); + q[1].Obj.Should().NotBeNull(); + q[1].Str.Should().BeNull(); + + q[2].Id.Should().BeNull(); + q[2].Gud.Should().BeNull(); + q[2].Obj.Should().NotBeNull(); + q[2].Str.Should().NotBeNull(); + + q[3].Id.Should().BeNull(); + q[3].Gud.Should().NotBeNull(); + q[3].Obj.Should().BeNull(); + q[3].Str.Should().NotBeNull(); + + q[4].Id.Should().BeNull(); + q[4].Gud.Should().NotBeNull(); + q[4].Obj.Should().NotBeNull(); + q[4].Str.Should().BeNull(); + } + + public class Foo + { + public Guid Id { get; set; } + public object Bar { get; set; } + } + + public class Bar + { + public Guid Id { get; set; } + public Person Person { get; set; } + } + + public class Qux + { + public int? Id { get; set; } + public Guid? Gud { get; set; } + public object Obj { get; set; } + public string Str { get; set; } + } +} + +public class Person +{ + public Guid? Guid { get; set; } + public string Name { get; set; } +} + +public static class ObjectExtensions +{ + public static Guid? NullableUuid(this Randomizer r) { - public static Guid? NullableUuid(this Randomizer r) - { - return r.Bool() ? r.Uuid() : (Guid?)null; - } + return r.Bool() ? r.Uuid() : (Guid?)null; } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue126.cs b/Source/Bogus.Tests/GitHubIssues/Issue126.cs index c2bedf0d..be79ecb1 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue126.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue126.cs @@ -5,74 +5,73 @@ using Xunit; using Xunit.Abstractions; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue126 : SeededTest { - public class Issue126 : SeededTest - { - private readonly ITestOutputHelper console; + private readonly ITestOutputHelper console; - public Issue126(ITestOutputHelper console) - { - this.console = console; - } + public Issue126(ITestOutputHelper console) + { + this.console = console; + } - public class CustomFaker : Faker where T : class + public class CustomFaker : Faker where T : class + { + public List Generate(int min, int max, string ruleSets = null) { - public List Generate(int min, int max, string ruleSets = null) - { - var n = this.FakerHub.Random.Number(min, max); - return this.Generate(n, ruleSets); - } + var n = this.FakerHub.Random.Number(min, max); + return this.Generate(n, ruleSets); } + } - [Fact] - public void can_generate_random_amount_by_derived_faker() - { - var faker = new CustomFaker() - .RuleFor(x => x.Item, f => f.Commerce.Product()) - .RuleFor(x => x.Quantity, f => f.Random.Number(1, 10)) - .RuleFor(x => x.OrderId, f => f.UniqueIndex) - as CustomFaker; + [Fact] + public void can_generate_random_amount_by_derived_faker() + { + var faker = new CustomFaker() + .RuleFor(x => x.Item, f => f.Commerce.Product()) + .RuleFor(x => x.Quantity, f => f.Random.Number(1, 10)) + .RuleFor(x => x.OrderId, f => f.UniqueIndex) + as CustomFaker; - var fakes = faker.Generate(1, 10); - fakes.Count.Should().BeGreaterOrEqualTo(1).And.BeLessOrEqualTo(10); - console.Dump(fakes.Count); - } + var fakes = faker.Generate(1, 10); + fakes.Count.Should().BeGreaterOrEqualTo(1).And.BeLessOrEqualTo(10); + console.Dump(fakes.Count); + } - [Fact] - public void can_generate_random_amount_with_extension_methods() - { - var faker = new Faker() - .RuleFor(x => x.Item, f => f.Commerce.Product()) - .RuleFor(x => x.Quantity, f => f.Random.Number(1, 10)) - .RuleFor(x => x.OrderId, f => f.UniqueIndex); + [Fact] + public void can_generate_random_amount_with_extension_methods() + { + var faker = new Faker() + .RuleFor(x => x.Item, f => f.Commerce.Product()) + .RuleFor(x => x.Quantity, f => f.Random.Number(1, 10)) + .RuleFor(x => x.OrderId, f => f.UniqueIndex); - var fakes = faker.Generate(1, 10); - fakes.Count.Should().BeGreaterOrEqualTo(1).And.BeLessOrEqualTo(10); - console.Dump(fakes.Count); - } + var fakes = faker.Generate(1, 10); + fakes.Count.Should().BeGreaterOrEqualTo(1).And.BeLessOrEqualTo(10); + console.Dump(fakes.Count); + } - [Fact] - public void can_generate_random_amount_with_builtin_generate_between_extension_method() - { - var faker = new Faker() - .RuleFor(x => x.Item, f => f.Commerce.Product()) - .RuleFor(x => x.Quantity, f => f.Random.Number(1, 10)) - .RuleFor(x => x.OrderId, f => f.UniqueIndex); + [Fact] + public void can_generate_random_amount_with_builtin_generate_between_extension_method() + { + var faker = new Faker() + .RuleFor(x => x.Item, f => f.Commerce.Product()) + .RuleFor(x => x.Quantity, f => f.Random.Number(1, 10)) + .RuleFor(x => x.OrderId, f => f.UniqueIndex); - var fakes = faker.GenerateBetween(2, 10); - fakes.Count.Should().BeGreaterOrEqualTo(2).And.BeLessOrEqualTo(10); - console.Dump(fakes.Count); - } + var fakes = faker.GenerateBetween(2, 10); + fakes.Count.Should().BeGreaterOrEqualTo(2).And.BeLessOrEqualTo(10); + console.Dump(fakes.Count); } +} - public static class ExtensionsForFakerT +public static class ExtensionsForFakerT +{ + public static List Generate(this Faker faker, int min, int max, string ruleSets = null) where T : class { - public static List Generate(this Faker faker, int min, int max, string ruleSets = null) where T : class - { - var r = new Randomizer(); - var n = r.Number(min, max); - return faker.Generate(n, ruleSets); - } + var r = new Randomizer(); + var n = r.Number(min, max); + return faker.Generate(n, ruleSets); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue13.cs b/Source/Bogus.Tests/GitHubIssues/Issue13.cs index 1bb57a7e..fe3d435a 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue13.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue13.cs @@ -2,110 +2,109 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue13 : SeededTest { - public class Issue13 : SeededTest + public class ReadOnly { - public class ReadOnly - { - public string Name; + public string Name; - public string NameReadOnly => Name; - } + public string NameReadOnly => Name; + } - [Fact] - public void issue_13_readonly_property() - { - var faker = new Faker() - .StrictMode(true) - .RuleFor(ro => ro.Name, f => f.Name.FirstName()); + [Fact] + public void issue_13_readonly_property() + { + var faker = new Faker() + .StrictMode(true) + .RuleFor(ro => ro.Name, f => f.Name.FirstName()); - faker.Validate().Should().BeTrue(); - faker.TypeProperties.Count.Should().Be(1); - } + faker.Validate().Should().BeTrue(); + faker.TypeProperties.Count.Should().Be(1); + } - [Fact] - public void issue_13_with_model() - { - var counter = 0; - - var faker = new Faker() - .StrictMode(true) - .RuleFor(c => c.SomeOtherId, f => counter++) - .RuleFor(c => c.SomeId, f => Guid.NewGuid()) - .RuleFor(c => c.SomeFutureDate, f => f.Date.Future()) - .RuleFor(c => c.SomePastDate, (f, b) => b.SomeFutureDate.AddHours(f.Random.Number(1, 24))) - .RuleFor(c => c.SomeStatusInt, (f, b) => (int)b.SomeExplicitInt) - .RuleFor(c => c.SomeExplicitInt, f => 2) - .RuleFor(c => c.SomeBool3, f => f.Random.Bool()) - .RuleFor(c => c.SomeBool2, f => f.Random.Bool()) - .RuleFor(c => c.SomeBool1, f => f.Random.Bool()) - .RuleFor(c => c.SomeOtherInt, f => f.Random.Number(1, 5)) - .RuleFor(c => c.SomeInt, f => 0) - .RuleFor(c => c.SomeOtherString, f => null) - .RuleFor(c => c.SomeOtherGuid, f => Guid.NewGuid()) - .RuleFor(c => c.SomeString, f => null) - .RuleFor(c => c.SomeComment, f => f.Lorem.Sentence()) - .RuleFor(c => c.SomeGuid, f => null) - .RuleFor(c => c.SomeTimestamp, f => null); - - faker.TypeProperties.Count.Should().Be(17); - - var fake = faker.Generate(); - fake.Dump(); - } + [Fact] + public void issue_13_with_model() + { + var counter = 0; + + var faker = new Faker() + .StrictMode(true) + .RuleFor(c => c.SomeOtherId, f => counter++) + .RuleFor(c => c.SomeId, f => Guid.NewGuid()) + .RuleFor(c => c.SomeFutureDate, f => f.Date.Future()) + .RuleFor(c => c.SomePastDate, (f, b) => b.SomeFutureDate.AddHours(f.Random.Number(1, 24))) + .RuleFor(c => c.SomeStatusInt, (f, b) => (int)b.SomeExplicitInt) + .RuleFor(c => c.SomeExplicitInt, f => 2) + .RuleFor(c => c.SomeBool3, f => f.Random.Bool()) + .RuleFor(c => c.SomeBool2, f => f.Random.Bool()) + .RuleFor(c => c.SomeBool1, f => f.Random.Bool()) + .RuleFor(c => c.SomeOtherInt, f => f.Random.Number(1, 5)) + .RuleFor(c => c.SomeInt, f => 0) + .RuleFor(c => c.SomeOtherString, f => null) + .RuleFor(c => c.SomeOtherGuid, f => Guid.NewGuid()) + .RuleFor(c => c.SomeString, f => null) + .RuleFor(c => c.SomeComment, f => f.Lorem.Sentence()) + .RuleFor(c => c.SomeGuid, f => null) + .RuleFor(c => c.SomeTimestamp, f => null); + + faker.TypeProperties.Count.Should().Be(17); + + var fake = faker.Generate(); + fake.Dump(); + } - public class TestObject - { - private DateTime? _lastTimeToUnbook; + public class TestObject + { + private DateTime? _lastTimeToUnbook; - public int SomeOtherId { get; set; } + public int SomeOtherId { get; set; } - public Guid SomeId { get; set; } + public Guid SomeId { get; set; } - public DateTime SomeFutureDate { get; set; } + public DateTime SomeFutureDate { get; set; } - public DateTime SomePastDate { get; set; } + public DateTime SomePastDate { get; set; } - public int SomeStatusInt { get; set; } + public int SomeStatusInt { get; set; } - public int SomeExplicitInt - { - get { return this.SomeStatusInt; } - set { this.SomeStatusInt = value; } - } + public int SomeExplicitInt + { + get { return this.SomeStatusInt; } + set { this.SomeStatusInt = value; } + } - public bool SomeBool3 { get; set; } + public bool SomeBool3 { get; set; } - public bool SomeBool2 { get; set; } + public bool SomeBool2 { get; set; } - public bool SomeBool1 { get; set; } + public bool SomeBool1 { get; set; } - public int SomeOtherInt { get; set; } + public int SomeOtherInt { get; set; } - public DateTime? ReadOnlyDateTime - { - get { return _lastTimeToUnbook; } - } + public DateTime? ReadOnlyDateTime + { + get { return _lastTimeToUnbook; } + } - public int SomeInt { get; set; } + public int SomeInt { get; set; } - public string SomeOtherString { get; set; } + public string SomeOtherString { get; set; } - public Guid SomeOtherGuid { get; set; } + public Guid SomeOtherGuid { get; set; } - public string SomeString { get; set; } + public string SomeString { get; set; } - public bool Someboolean - { - get { return !this.SomeTimestamp.HasValue; } - } + public bool Someboolean + { + get { return !this.SomeTimestamp.HasValue; } + } - public DateTime? SomeTimestamp { get; set; } + public DateTime? SomeTimestamp { get; set; } - public Guid? SomeGuid { get; set; } + public Guid? SomeGuid { get; set; } - public string SomeComment { get; set; } - } + public string SomeComment { get; set; } } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue132.cs b/Source/Bogus.Tests/GitHubIssues/Issue132.cs index 07f666a6..bda3c820 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue132.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue132.cs @@ -5,165 +5,164 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue132 : SeededTest { - public class Issue132 : SeededTest + [Fact] + public void should_throw_exception_on_invalid_locale_dataset() + { + Action a = () => new Lorem("wtf_locale"); + a.Should().Throw(); + } + + [Fact] + public void should_throw_exception_on_invalid_locale_with_faker_t() + { + Action a = () => new Faker("yo yo yo"); + + a.Should().Throw(); + } + + [Fact] + public void should_throw_exception_on_invalid_locate_with_faker() + { + Action a = () => new Faker("fe fi fo fum"); + + a.Should().Throw(); + } + + [Fact] + public void ensure_the_project_url_exists() + { + + Action a = () => new Lorem("LOCALE"); + + //make sure the message has a link back to the project site. + //test exists here because we're using AssemblyDescription attribute + //and in case that changes, we need to be aware of it. + + a.Should().Throw() + .And.Message + .Should().Contain("https://github.com/bchavez/Bogus"); + + } + + [Fact] + public void fr_locale() + { + CultureInfo.GetCultureInfo("fr-CA") + .ToBogusLocale() + .Should().Be("fr_CA"); + + CultureInfo.GetCultureInfo("fr-BE") + .ToBogusLocale() + .Should().Be("fr"); + } + + + [Fact] + public void nb_NO_locale() + { + var nnNO = CultureInfo.GetCultureInfo("nn-NO"); + nnNO.ToBogusLocale() + .Should().Be("nb_NO"); + + var nbNO = CultureInfo.GetCultureInfo("nb-NO"); + nbNO.ToBogusLocale() + .Should().Be("nb_NO"); + + var no = CultureInfo.GetCultureInfo("no"); + no.ToBogusLocale() + .Should().Be("nb_NO"); + + var nb = CultureInfo.GetCultureInfo("nb"); + nb.ToBogusLocale() + .Should().Be("nb_NO"); + + var nn = CultureInfo.GetCultureInfo("nn"); + nn.ToBogusLocale() + .Should().Be("nb_NO"); + } + + + [Fact] + public void id_ID_locale() + { + CultureInfo.GetCultureInfo("id-ID") + .ToBogusLocale() + .Should().Be("id_ID"); + + CultureInfo.GetCultureInfo("id") + .ToBogusLocale() + .Should().Be("id_ID"); + } + + [Fact] + public void ne_locale() + { + CultureInfo.GetCultureInfo("ne-NP") + .ToBogusLocale() + .Should().Be("ne"); + + CultureInfo.GetCultureInfo("ne") + .ToBogusLocale() + .Should().Be("ne"); + } + + [Fact] + public void ge_locale() + { + CultureInfo.GetCultureInfo("ka-GE") + .ToBogusLocale() + .Should().Be("ge"); + + CultureInfo.GetCultureInfo("ka") + .ToBogusLocale() + .Should().Be("ge"); + } + + [Fact] + public void ind_locale() + { + CultureInfo.GetCultureInfo("en-IN") + .ToBogusLocale() + .Should().Be("en_IND"); + } + + [Fact] + public void cz_locale() + { + CultureInfo.GetCultureInfo("cs") + .ToBogusLocale() + .Should().Be("cz"); + + CultureInfo.GetCultureInfo("cs-CZ") + .ToBogusLocale() + .Should().Be("cz"); + } + + [Fact] + public void en_US_locale() { - [Fact] - public void should_throw_exception_on_invalid_locale_dataset() - { - Action a = () => new Lorem("wtf_locale"); - a.Should().Throw(); - } - - [Fact] - public void should_throw_exception_on_invalid_locale_with_faker_t() - { - Action a = () => new Faker("yo yo yo"); - - a.Should().Throw(); - } - - [Fact] - public void should_throw_exception_on_invalid_locate_with_faker() - { - Action a = () => new Faker("fe fi fo fum"); - - a.Should().Throw(); - } - - [Fact] - public void ensure_the_project_url_exists() - { - - Action a = () => new Lorem("LOCALE"); - - //make sure the message has a link back to the project site. - //test exists here because we're using AssemblyDescription attribute - //and in case that changes, we need to be aware of it. - - a.Should().Throw() - .And.Message - .Should().Contain("https://github.com/bchavez/Bogus"); - - } - - [Fact] - public void fr_locale() - { - CultureInfo.GetCultureInfo("fr-CA") - .ToBogusLocale() - .Should().Be("fr_CA"); - - CultureInfo.GetCultureInfo("fr-BE") - .ToBogusLocale() - .Should().Be("fr"); - } - - - [Fact] - public void nb_NO_locale() - { - var nnNO = CultureInfo.GetCultureInfo("nn-NO"); - nnNO.ToBogusLocale() - .Should().Be("nb_NO"); - - var nbNO = CultureInfo.GetCultureInfo("nb-NO"); - nbNO.ToBogusLocale() - .Should().Be("nb_NO"); - - var no = CultureInfo.GetCultureInfo("no"); - no.ToBogusLocale() - .Should().Be("nb_NO"); - - var nb = CultureInfo.GetCultureInfo("nb"); - nb.ToBogusLocale() - .Should().Be("nb_NO"); - - var nn = CultureInfo.GetCultureInfo("nn"); - nn.ToBogusLocale() - .Should().Be("nb_NO"); - } - - - [Fact] - public void id_ID_locale() - { - CultureInfo.GetCultureInfo("id-ID") - .ToBogusLocale() - .Should().Be("id_ID"); - - CultureInfo.GetCultureInfo("id") - .ToBogusLocale() - .Should().Be("id_ID"); - } - - [Fact] - public void ne_locale() - { - CultureInfo.GetCultureInfo("ne-NP") - .ToBogusLocale() - .Should().Be("ne"); - - CultureInfo.GetCultureInfo("ne") - .ToBogusLocale() - .Should().Be("ne"); - } - - [Fact] - public void ge_locale() - { - CultureInfo.GetCultureInfo("ka-GE") - .ToBogusLocale() - .Should().Be("ge"); - - CultureInfo.GetCultureInfo("ka") - .ToBogusLocale() - .Should().Be("ge"); - } - - [Fact] - public void ind_locale() - { - CultureInfo.GetCultureInfo("en-IN") - .ToBogusLocale() - .Should().Be("en_IND"); - } - - [Fact] - public void cz_locale() - { - CultureInfo.GetCultureInfo("cs") - .ToBogusLocale() - .Should().Be("cz"); - - CultureInfo.GetCultureInfo("cs-CZ") - .ToBogusLocale() - .Should().Be("cz"); - } - - [Fact] - public void en_US_locale() - { - CultureInfo.GetCultureInfo("en-US") - .ToBogusLocale() - .Should().Be("en_US"); - } - - [Fact] - public void de_locale() - { - CultureInfo.GetCultureInfo("de-AT") - .ToBogusLocale() - .Should().Be("de_AT"); - - CultureInfo.GetCultureInfo("de-CH") - .ToBogusLocale() - .Should().Be("de_CH"); - - CultureInfo.GetCultureInfo("de-LI") - .ToBogusLocale() - .Should().Be("de"); - } + CultureInfo.GetCultureInfo("en-US") + .ToBogusLocale() + .Should().Be("en_US"); + } + + [Fact] + public void de_locale() + { + CultureInfo.GetCultureInfo("de-AT") + .ToBogusLocale() + .Should().Be("de_AT"); + + CultureInfo.GetCultureInfo("de-CH") + .ToBogusLocale() + .Should().Be("de_CH"); + + CultureInfo.GetCultureInfo("de-LI") + .ToBogusLocale() + .Should().Be("de"); } } diff --git a/Source/Bogus.Tests/GitHubIssues/Issue134.cs b/Source/Bogus.Tests/GitHubIssues/Issue134.cs index e46c6455..1021111a 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue134.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue134.cs @@ -4,55 +4,54 @@ using Xunit; using Z.ExtensionMethods; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue134 : SeededTest { - public class Issue134 : SeededTest + [Fact] + public void can_make_rules_from_string() { - [Fact] - public void can_make_rules_from_string() - { - var rulesFromTextFile = - @" + var rulesFromTextFile = + @" FirstName, {{name.firstName}} LastName, {{name.lastName}} StreetAddress, {{address.StreetAddress}} "; - var faker = new HandlebarFaker() - .LoadRulesFromString(rulesFromTextFile); + var faker = new HandlebarFaker() + .LoadRulesFromString(rulesFromTextFile); - var foo = faker.Generate(); + var foo = faker.Generate(); - foo.FirstName.Should().Be("Lee"); - foo.LastName.Should().Be("Brekke"); - foo.StreetAddress.Should().Be("6439 Lindsey Cape"); - } + foo.FirstName.Should().Be("Lee"); + foo.LastName.Should().Be("Brekke"); + foo.StreetAddress.Should().Be("6439 Lindsey Cape"); } +} - public class Foo - { - public string FirstName { get; set; } - public string LastName { get; set; } - public string StreetAddress { get; set; } - } +public class Foo +{ + public string FirstName { get; set; } + public string LastName { get; set; } + public string StreetAddress { get; set; } +} - public class HandlebarFaker : Faker where T : class +public class HandlebarFaker : Faker where T : class +{ + public HandlebarFaker LoadRulesFromString(string rules) { - public HandlebarFaker LoadRulesFromString(string rules) - { - var lines = rules.Split( - new[] {"\r\n", "\r", "\n"}, StringSplitOptions.RemoveEmptyEntries) - .Where( s => !s.IsNullOrWhiteSpace()); - - foreach( var line in lines ) - { - var parts = line.Split(','); - var memberName = parts[0].Trim(); - var handlebarRule = parts[1].Trim(); + var lines = rules.Split( + new[] {"\r\n", "\r", "\n"}, StringSplitOptions.RemoveEmptyEntries) + .Where( s => !s.IsNullOrWhiteSpace()); - this.RuleFor(memberName, f => f.Parse($"{handlebarRule}")); - } + foreach( var line in lines ) + { + var parts = line.Split(','); + var memberName = parts[0].Trim(); + var handlebarRule = parts[1].Trim(); - return this; + this.RuleFor(memberName, f => f.Parse($"{handlebarRule}")); } + + return this; } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue143.cs b/Source/Bogus.Tests/GitHubIssues/Issue143.cs index 3d32e084..76e776a0 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue143.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue143.cs @@ -3,51 +3,50 @@ using Xunit; using Xunit.Abstractions; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue143 : SeededTest { - public class Issue143 : SeededTest + private readonly ITestOutputHelper console; + + public Issue143(ITestOutputHelper console) + { + this.console = console; + } + + private void RunAnotherPrecedingFaker() + { + var fakerRule = new Faker() + .RuleFor(o => o.OrderId, f => f.IndexGlobal) + .RuleFor(o => o.Item, f => f.Commerce.Product()) + .RuleFor(o => o.Quantity, f => f.Random.Number(1, 3)); + + var ordersRules = fakerRule.Generate(5); + console.Dump(ordersRules); + } + + [Fact] + public void IndexGlobal_should_be_incremented_when_CustomInstantiator_is_only_used() { - private readonly ITestOutputHelper console; - - public Issue143(ITestOutputHelper console) - { - this.console = console; - } - - private void RunAnotherPrecedingFaker() - { - var fakerRule = new Faker() - .RuleFor(o => o.OrderId, f => f.IndexGlobal) - .RuleFor(o => o.Item, f => f.Commerce.Product()) - .RuleFor(o => o.Quantity, f => f.Random.Number(1, 3)); - - var ordersRules = fakerRule.Generate(5); - console.Dump(ordersRules); - } - - [Fact] - public void IndexGlobal_should_be_incremented_when_CustomInstantiator_is_only_used() - { - //Uncomment to test to see what happens if a previous - //faker is called that influences IndexGlobal. - //RunAnotherPrecedingFaker(); - - var faker = new Faker() - .CustomInstantiator(f => new Models.Order - { - OrderId = f.IndexGlobal, - Item = f.Commerce.Product(), - Quantity = f.Random.Number(1, 3) - }); - - var orders = faker.Generate(5); - //console.Dump(orders); - - var oids = orders.Select(o => o.OrderId).ToList(); - - var start = oids[0]; - - oids.Should().Equal(start, start + 1, start + 2, start + 3, start + 4); - } + //Uncomment to test to see what happens if a previous + //faker is called that influences IndexGlobal. + //RunAnotherPrecedingFaker(); + + var faker = new Faker() + .CustomInstantiator(f => new Models.Order + { + OrderId = f.IndexGlobal, + Item = f.Commerce.Product(), + Quantity = f.Random.Number(1, 3) + }); + + var orders = faker.Generate(5); + //console.Dump(orders); + + var oids = orders.Select(o => o.OrderId).ToList(); + + var start = oids[0]; + + oids.Should().Equal(start, start + 1, start + 2, start + 3, start + 4); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue152.cs b/Source/Bogus.Tests/GitHubIssues/Issue152.cs index 9e5268f5..3e74f78b 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue152.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue152.cs @@ -1,19 +1,18 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue152 : SeededTest { - public class Issue152 : SeededTest + [Fact] + public void make_unique_email_easier_to_generate() { - [Fact] - public void make_unique_email_easier_to_generate() - { - var f = new Faker(); + var f = new Faker(); - var email = f.Internet.Email(uniqueSuffix: "fff"); - email.Should().Contain("fff@"); + var email = f.Internet.Email(uniqueSuffix: "fff"); + email.Should().Contain("fff@"); - f.Internet.Email(uniqueSuffix: f.UniqueIndex.ToString()); - } + f.Internet.Email(uniqueSuffix: f.UniqueIndex.ToString()); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue168.cs b/Source/Bogus.Tests/GitHubIssues/Issue168.cs index 1ddd1425..7d4da588 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue168.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue168.cs @@ -1,16 +1,15 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue168 : SeededTest { - public class Issue168 : SeededTest + [Fact] + public void make_sure_person_card_has_a_state() { - [Fact] - public void make_sure_person_card_has_a_state() - { - var p = new Bogus.Person(); + var p = new Bogus.Person(); - p.Address.State.Should().NotBeNullOrWhiteSpace(); - } + p.Address.State.Should().NotBeNullOrWhiteSpace(); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue169.cs b/Source/Bogus.Tests/GitHubIssues/Issue169.cs index 9fd51ed0..eb5d227e 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue169.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue169.cs @@ -1,16 +1,15 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue169 : SeededTest { - public class Issue169 : SeededTest + [Fact] + public void date_weekday_should_generate_a_weekday() { - [Fact] - public void date_weekday_should_generate_a_weekday() - { - var d = new DataSets.Date(); + var d = new DataSets.Date(); - d.Weekday().Should().Be("Thursday"); - } + d.Weekday().Should().Be("Thursday"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue178.cs b/Source/Bogus.Tests/GitHubIssues/Issue178.cs index 97a13e9a..9dd71d45 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue178.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue178.cs @@ -3,49 +3,48 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue178 : SeededTest { - public class Issue178 : SeededTest + [Fact] + public void weighted_null_check() + { + var f = new Faker(); + var mostlyNull = Enumerable.Range(1, 100) + .Select(n => (int?)n.OrNull(f, 0.9f)) + .Count( n => !n.HasValue); + + mostlyNull.Should().BeGreaterThan(80); + + var mostlyNotNull = Enumerable.Range(1, 100) + .Select(n => (int?)n.OrNull(f, 0.1f)) + .Count(n => !n.HasValue); + + mostlyNotNull.Should().BeLessThan(20); + } + + [Fact] + public void weighted_default_check() { - [Fact] - public void weighted_null_check() - { - var f = new Faker(); - var mostlyNull = Enumerable.Range(1, 100) - .Select(n => (int?)n.OrNull(f, 0.9f)) - .Count( n => !n.HasValue); - - mostlyNull.Should().BeGreaterThan(80); - - var mostlyNotNull = Enumerable.Range(1, 100) - .Select(n => (int?)n.OrNull(f, 0.1f)) - .Count(n => !n.HasValue); - - mostlyNotNull.Should().BeLessThan(20); - } - - [Fact] - public void weighted_default_check() - { - var f = new Faker(); - var mostlyDefault = Enumerable.Range(1, 100) - .Select(n => n.OrDefault(f, 0.9f)) - .Count(n => n == default); - - mostlyDefault.Should().BeGreaterThan(80); - - var mostlyNotDefault = Enumerable.Range(1, 100) - .Select(n => n.OrDefault(f, 0.1f)) - .Count(n => n == default); - - mostlyNotDefault.Should().BeLessThan(20); - - var mostlyNotDefaultObject = Enumerable.Range(1, 100) - .Select( n => new object()) - .Select(s => s.OrDefault(f, 0.1f)) - .Count(s => s == null); - - mostlyNotDefaultObject.Should().BeLessThan(20); - } + var f = new Faker(); + var mostlyDefault = Enumerable.Range(1, 100) + .Select(n => n.OrDefault(f, 0.9f)) + .Count(n => n == default); + + mostlyDefault.Should().BeGreaterThan(80); + + var mostlyNotDefault = Enumerable.Range(1, 100) + .Select(n => n.OrDefault(f, 0.1f)) + .Count(n => n == default); + + mostlyNotDefault.Should().BeLessThan(20); + + var mostlyNotDefaultObject = Enumerable.Range(1, 100) + .Select( n => new object()) + .Select(s => s.OrDefault(f, 0.1f)) + .Count(s => s == null); + + mostlyNotDefaultObject.Should().BeLessThan(20); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue179.cs b/Source/Bogus.Tests/GitHubIssues/Issue179.cs index 7cab46a3..d0efbfc3 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue179.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue179.cs @@ -3,69 +3,68 @@ using Xunit.Abstractions; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue179 : SeededTest { - public class Issue179 : SeededTest - { - private readonly ITestOutputHelper console; + private readonly ITestOutputHelper console; - public Issue179(ITestOutputHelper console) - { - this.console = console; - } + public Issue179(ITestOutputHelper console) + { + this.console = console; + } - [Fact] - public void should_be_able_to_set_non_public_members_of_T() - { - var fooFaker = new Faker() - .RuleFor(x => x.Baz, f => f.Random.String2(10)) - .RuleFor(x => x.Bar, f => f.Random.String2(10)) - .RuleFor( x => x.Normal, f => f.Random.String2(10)) - ; + [Fact] + public void should_be_able_to_set_non_public_members_of_T() + { + var fooFaker = new Faker() + .RuleFor(x => x.Baz, f => f.Random.String2(10)) + .RuleFor(x => x.Bar, f => f.Random.String2(10)) + .RuleFor( x => x.Normal, f => f.Random.String2(10)) + ; - var foos = fooFaker.Generate(10); + var foos = fooFaker.Generate(10); - foreach (var foo in foos) - { - console.WriteLine($"{foo.Baz} / {foo.Bar} / {foo.Normal}"); - foo.Baz.Should().NotBeNullOrWhiteSpace(); - foo.Bar.Should().NotBeNullOrWhiteSpace(); - foo.Normal.Should().NotBeNullOrWhiteSpace(); - } + foreach (var foo in foos) + { + console.WriteLine($"{foo.Baz} / {foo.Bar} / {foo.Normal}"); + foo.Baz.Should().NotBeNullOrWhiteSpace(); + foo.Bar.Should().NotBeNullOrWhiteSpace(); + foo.Normal.Should().NotBeNullOrWhiteSpace(); } + } - [Fact] - public void can_set_members_on_internal_class() - { - var boxFaker = new Faker() - .RuleFor(x => x.Bub, f => f.Random.String2(10)) - .RuleFor(x => x.Normal, f => f.Random.String2(10)) - ; + [Fact] + public void can_set_members_on_internal_class() + { + var boxFaker = new Faker() + .RuleFor(x => x.Bub, f => f.Random.String2(10)) + .RuleFor(x => x.Normal, f => f.Random.String2(10)) + ; - var boxes = boxFaker.Generate(10); + var boxes = boxFaker.Generate(10); - foreach( var box in boxes ) - { - console.WriteLine($"{box.Bub} / {box.Normal}"); - box.Bub.Should().NotBeNullOrWhiteSpace(); - box.Normal.Should().NotBeNullOrWhiteSpace(); - } + foreach( var box in boxes ) + { + console.WriteLine($"{box.Bub} / {box.Normal}"); + box.Bub.Should().NotBeNullOrWhiteSpace(); + box.Normal.Should().NotBeNullOrWhiteSpace(); } } +} - public class Buz - { - public string Baz { get; internal set; } +public class Buz +{ + public string Baz { get; internal set; } - internal string Bar { get; set; } + internal string Bar { get; set; } - public string Normal { get; set; } - } + public string Normal { get; set; } +} - internal class Box - { - internal string Bub { get; private set; } - public string Normal { get; set; } - } +internal class Box +{ + internal string Bub { get; private set; } + public string Normal { get; set; } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue192.cs b/Source/Bogus.Tests/GitHubIssues/Issue192.cs index 7023dcce..b6f32a9f 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue192.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue192.cs @@ -1,25 +1,24 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue192 : SeededTest { - public class Issue192 : SeededTest - { - [Fact] - public void no_company_suffix_should_not_throw() - { - var f = new Faker("az"); - var s = f.Random.ArrayElement(f.Company.Suffixes()); - s.Should().Be("Holdinqlər"); - } + [Fact] + public void no_company_suffix_should_not_throw() + { + var f = new Faker("az"); + var s = f.Random.ArrayElement(f.Company.Suffixes()); + s.Should().Be("Holdinqlər"); + } - [Fact] - public void company_name_should_work_in_az() - { - var f = new Faker("az"); + [Fact] + public void company_name_should_work_in_az() + { + var f = new Faker("az"); - f.Company.CompanyName(0).Should().Be("Əfəndiyeva Holdinqlər"); - } + f.Company.CompanyName(0).Should().Be("Əfəndiyeva Holdinqlər"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue193.cs b/Source/Bogus.Tests/GitHubIssues/Issue193.cs index 1c24ca9b..124d80ef 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue193.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue193.cs @@ -2,119 +2,118 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue193 : SeededTest { - public class Issue193 : SeededTest + [Fact] + public void tr_locale_should_have_real_state_name() { - [Fact] - public void tr_locale_should_have_real_state_name() - { - var f = new Faker("tr"); - - f.Address.State().Should().Be("Kirklareli"); - } - - [Fact] - public void can_extend_address_with_my_own_iso3166tr() - { - var f = new Faker("tr"); - - var state = f.Address.StateIso3166(); - state.Name.Should().Be("Kirklareli"); - state.Code.Should().Be("TR-39"); - } + var f = new Faker("tr"); + + f.Address.State().Should().Be("Kirklareli"); } - public static class ExtensionsForTrLocale + [Fact] + public void can_extend_address_with_my_own_iso3166tr() { - private static (string, string)[] Iso3166TR = - { - ("TR-01", "Adana"), - ("TR-02", "Adiyaman"), - ("TR-03", "Afyonkarahisar"), - ("TR-04", "Agri"), - ("TR-68", "Aksaray"), - ("TR-05", "Amasya"), - ("TR-06", "Ankara"), - ("TR-07", "Antalya"), - ("TR-75", "Ardahan"), - ("TR-08", "Artvin"), - ("TR-09", "Aydin"), - ("TR-10", "Balikesir"), - ("TR-74", "Bartin"), - ("TR-72", "Batman"), - ("TR-69", "Bayburt"), - ("TR-11", "Bilecik"), - ("TR-12", "Bingöl"), - ("TR-13", "Bitlis"), - ("TR-14", "Bolu"), - ("TR-15", "Burdur"), - ("TR-16", "Bursa"), - ("TR-17", "Çanakkale"), - ("TR-18", "Çankiri"), - ("TR-19", "Çorum"), - ("TR-20", "Denizli"), - ("TR-21", "Diyarbakir"), - ("TR-81", "Düzce"), - ("TR-22", "Edirne"), - ("TR-23", "Elazig"), - ("TR-24", "Erzincan"), - ("TR-25", "Erzurum"), - ("TR-26", "Eskisehir"), - ("TR-27", "Gaziantep"), - ("TR-28", "Giresun"), - ("TR-29", "Gümüshane"), - ("TR-30", "Hakkâri"), - ("TR-31", "Hatay"), - ("TR-76", "Igdir"), - ("TR-32", "Isparta"), - ("TR-34", "Istanbul"), - ("TR-35", "Izmir"), - ("TR-46", "Kahramanmaras"), - ("TR-78", "Karabük"), - ("TR-70", "Karaman"), - ("TR-36", "Kars"), - ("TR-37", "Kastamonu"), - ("TR-38", "Kayseri"), - ("TR-71", "Kirikkale"), - ("TR-39", "Kirklareli"), - ("TR-40", "Kirsehir"), - ("TR-79", "Kilis"), - ("TR-41", "Kocaeli"), - ("TR-42", "Konya"), - ("TR-43", "Kütahya"), - ("TR-44", "Malatya"), - ("TR-45", "Manisa"), - ("TR-47", "Mardin"), - ("TR-33", "Mersin"), - ("TR-48", "Mugla"), - ("TR-49", "Mus"), - ("TR-50", "Nevsehir"), - ("TR-51", "Nigde"), - ("TR-52", "Ordu"), - ("TR-80", "Osmaniye"), - ("TR-53", "Rize"), - ("TR-54", "Sakarya"), - ("TR-55", "Samsun"), - ("TR-56", "Siirt"), - ("TR-57", "Sinop"), - ("TR-58", "Sivas"), - ("TR-63", "Sanliurfa"), - ("TR-73", "Sirnak"), - ("TR-59", "Tekirdag"), - ("TR-60", "Tokat"), - ("TR-61", "Trabzon"), - ("TR-62", "Tunceli"), - ("TR-64", "Usak"), - ("TR-65", "Van"), - ("TR-77", "Yalova"), - ("TR-66", "Yozgat"), - ("TR-67", "Zonguldak") - }; + var f = new Faker("tr"); - public static (string Code, string Name) StateIso3166(this Address address) + var state = f.Address.StateIso3166(); + state.Name.Should().Be("Kirklareli"); + state.Code.Should().Be("TR-39"); + } +} + +public static class ExtensionsForTrLocale +{ + private static (string, string)[] Iso3166TR = { - return address.Random.ArrayElement(Iso3166TR); - } + ("TR-01", "Adana"), + ("TR-02", "Adiyaman"), + ("TR-03", "Afyonkarahisar"), + ("TR-04", "Agri"), + ("TR-68", "Aksaray"), + ("TR-05", "Amasya"), + ("TR-06", "Ankara"), + ("TR-07", "Antalya"), + ("TR-75", "Ardahan"), + ("TR-08", "Artvin"), + ("TR-09", "Aydin"), + ("TR-10", "Balikesir"), + ("TR-74", "Bartin"), + ("TR-72", "Batman"), + ("TR-69", "Bayburt"), + ("TR-11", "Bilecik"), + ("TR-12", "Bingöl"), + ("TR-13", "Bitlis"), + ("TR-14", "Bolu"), + ("TR-15", "Burdur"), + ("TR-16", "Bursa"), + ("TR-17", "Çanakkale"), + ("TR-18", "Çankiri"), + ("TR-19", "Çorum"), + ("TR-20", "Denizli"), + ("TR-21", "Diyarbakir"), + ("TR-81", "Düzce"), + ("TR-22", "Edirne"), + ("TR-23", "Elazig"), + ("TR-24", "Erzincan"), + ("TR-25", "Erzurum"), + ("TR-26", "Eskisehir"), + ("TR-27", "Gaziantep"), + ("TR-28", "Giresun"), + ("TR-29", "Gümüshane"), + ("TR-30", "Hakkâri"), + ("TR-31", "Hatay"), + ("TR-76", "Igdir"), + ("TR-32", "Isparta"), + ("TR-34", "Istanbul"), + ("TR-35", "Izmir"), + ("TR-46", "Kahramanmaras"), + ("TR-78", "Karabük"), + ("TR-70", "Karaman"), + ("TR-36", "Kars"), + ("TR-37", "Kastamonu"), + ("TR-38", "Kayseri"), + ("TR-71", "Kirikkale"), + ("TR-39", "Kirklareli"), + ("TR-40", "Kirsehir"), + ("TR-79", "Kilis"), + ("TR-41", "Kocaeli"), + ("TR-42", "Konya"), + ("TR-43", "Kütahya"), + ("TR-44", "Malatya"), + ("TR-45", "Manisa"), + ("TR-47", "Mardin"), + ("TR-33", "Mersin"), + ("TR-48", "Mugla"), + ("TR-49", "Mus"), + ("TR-50", "Nevsehir"), + ("TR-51", "Nigde"), + ("TR-52", "Ordu"), + ("TR-80", "Osmaniye"), + ("TR-53", "Rize"), + ("TR-54", "Sakarya"), + ("TR-55", "Samsun"), + ("TR-56", "Siirt"), + ("TR-57", "Sinop"), + ("TR-58", "Sivas"), + ("TR-63", "Sanliurfa"), + ("TR-73", "Sirnak"), + ("TR-59", "Tekirdag"), + ("TR-60", "Tokat"), + ("TR-61", "Trabzon"), + ("TR-62", "Tunceli"), + ("TR-64", "Usak"), + ("TR-65", "Van"), + ("TR-77", "Yalova"), + ("TR-66", "Yozgat"), + ("TR-67", "Zonguldak") + }; + + public static (string Code, string Name) StateIso3166(this Address address) + { + return address.Random.ArrayElement(Iso3166TR); } } diff --git a/Source/Bogus.Tests/GitHubIssues/Issue218.cs b/Source/Bogus.Tests/GitHubIssues/Issue218.cs index 12e36456..22fd01dc 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue218.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue218.cs @@ -3,54 +3,53 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue218 : SeededTest { - public class Issue218 : SeededTest + [Fact] + public void global_strict_mode_should_throw_on_incomplete_rules() { - [Fact] - public void global_strict_mode_should_throw_on_incomplete_rules() - { - Faker.DefaultStrictMode = true; + Faker.DefaultStrictMode = true; - var orderFaker = new Faker() - .RuleFor(x => x.Item, f => f.Commerce.Product()); + var orderFaker = new Faker() + .RuleFor(x => x.Item, f => f.Commerce.Product()); - Action gen = () => orderFaker.Generate(); + Action gen = () => orderFaker.Generate(); - gen.Should().Throw(); + gen.Should().Throw(); - Faker.DefaultStrictMode = false; - } + Faker.DefaultStrictMode = false; + } - [Fact] - public void local_struct_mode_faker_t_scope_should_throw_on_incomplete_rules() - { - Faker.DefaultStrictMode = false; + [Fact] + public void local_struct_mode_faker_t_scope_should_throw_on_incomplete_rules() + { + Faker.DefaultStrictMode = false; - var orderFaker = new Faker() - .StrictMode(true) - .RuleFor(x => x.Item, f => f.Commerce.Product()); + var orderFaker = new Faker() + .StrictMode(true) + .RuleFor(x => x.Item, f => f.Commerce.Product()); - Action gen = () => orderFaker.Generate(); + Action gen = () => orderFaker.Generate(); - gen.Should().Throw(); - } + gen.Should().Throw(); + } - [Fact] - public void local_strict_mode_should_take_precedence_always() - { - Faker.DefaultStrictMode = true; + [Fact] + public void local_strict_mode_should_take_precedence_always() + { + Faker.DefaultStrictMode = true; - var orderFaker = new Faker() - .StrictMode(false) - .RuleFor(x => x.Item, f => f.Commerce.Product()); + var orderFaker = new Faker() + .StrictMode(false) + .RuleFor(x => x.Item, f => f.Commerce.Product()); - Action gen = () => orderFaker.Generate(); + Action gen = () => orderFaker.Generate(); - gen.Should().NotThrow(); + gen.Should().NotThrow(); - Faker.DefaultStrictMode = false; - } + Faker.DefaultStrictMode = false; } } diff --git a/Source/Bogus.Tests/GitHubIssues/Issue225.cs b/Source/Bogus.Tests/GitHubIssues/Issue225.cs index c6da3729..c4206b52 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue225.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue225.cs @@ -3,36 +3,35 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue225 : SeededTest { - public class Issue225 : SeededTest + [Fact] + public void can_generate_sane_email_addresses_in_different_locales() { - [Fact] - public void can_generate_sane_email_addresses_in_different_locales() - { - var p = new Bogus.Person("ru"); - p.FullName.Should().Be("Анастасия Евсеева"); - p.Email.Should().Be("Anastasiya69@gmail.com"); - } + var p = new Bogus.Person("ru"); + p.FullName.Should().Be("Анастасия Евсеева"); + p.Email.Should().Be("Anastasiya69@gmail.com"); + } - [Fact] - public void can_generate_sane_email_address_from_ru() - { - var i = new Internet(); - i.Email("Анна", "Фомина").Should().Be("Anna81@yahoo.com"); - } + [Fact] + public void can_generate_sane_email_address_from_ru() + { + var i = new Internet(); + i.Email("Анна", "Фомина").Should().Be("Anna81@yahoo.com"); + } - [Fact] - public void can_generate_email_without_transliteration() - { - var i = new Internet(); - i.Email("Анна", "Фомина").Should().Be("Anna81@yahoo.com"); - } + [Fact] + public void can_generate_email_without_transliteration() + { + var i = new Internet(); + i.Email("Анна", "Фомина").Should().Be("Anna81@yahoo.com"); + } - [Fact] - public void simple_translation() - { - "Анна Фомина".Transliterate().Should().Be("Anna Fomina"); - } + [Fact] + public void simple_translation() + { + "Анна Фомина".Transliterate().Should().Be("Anna Fomina"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue23.cs b/Source/Bogus.Tests/GitHubIssues/Issue23.cs index 99eea9cb..831104d7 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue23.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue23.cs @@ -1,24 +1,23 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue23 : SeededTest { - public class Issue23 : SeededTest + public class TestClass { - public class TestClass - { - public string Value { get; set; } - } + public string Value { get; set; } + } - [Fact] - public void issue_23_should_be_able_to_generate_random_word_without_exception() + [Fact] + public void issue_23_should_be_able_to_generate_random_word_without_exception() + { + var faker = new Faker(); + faker.RuleFor(x => x.Value, faker1 => faker1.Random.Word()); + foreach( var item in faker.Generate(1000) ) { - var faker = new Faker(); - faker.RuleFor(x => x.Value, faker1 => faker1.Random.Word()); - foreach( var item in faker.Generate(1000) ) - { - item.Value.Should().NotBeNullOrWhiteSpace(); - } + item.Value.Should().NotBeNullOrWhiteSpace(); } } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue232.cs b/Source/Bogus.Tests/GitHubIssues/Issue232.cs index 71eb6bd6..b855af50 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue232.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue232.cs @@ -5,41 +5,40 @@ using Xunit; using Xunit.Abstractions; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue232 : SeededTest { - public class Issue232 : SeededTest - { - private readonly ITestOutputHelper console; + private readonly ITestOutputHelper console; - public Issue232(ITestOutputHelper console) - { - this.console = console; - } + public Issue232(ITestOutputHelper console) + { + this.console = console; + } - [Fact] - public void default_value_checks() - { - var f = new Faker(); - var mostlyDefault = Enumerable.Range(1, 100) - .Select(n => n.OrDefault(f, 0.9f, 777)) - .Count(n => n == 777); + [Fact] + public void default_value_checks() + { + var f = new Faker(); + var mostlyDefault = Enumerable.Range(1, 100) + .Select(n => n.OrDefault(f, 0.9f, 777)) + .Count(n => n == 777); - mostlyDefault.Should().BeGreaterThan(80); + mostlyDefault.Should().BeGreaterThan(80); - var mostlyNotDefault = Enumerable.Range(1, 100) - .Select(n => n.OrDefault(f, 0.1f, 7777)) - .Count(n => n == 7777); + var mostlyNotDefault = Enumerable.Range(1, 100) + .Select(n => n.OrDefault(f, 0.1f, 7777)) + .Count(n => n == 7777); - mostlyNotDefault.Should().BeLessThan(20); + mostlyNotDefault.Should().BeLessThan(20); - var mark = new Guid("669248FB-6FFA-4912-B93E-12611266E18F"); + var mark = new Guid("669248FB-6FFA-4912-B93E-12611266E18F"); - var mostlyMarkObjects = Enumerable.Range(1, 100) - .Select(n => new object()) - .Select(s => s.OrDefault(f, 0.9f, mark)) - .Count(s => s is Guid g && g == mark); + var mostlyMarkObjects = Enumerable.Range(1, 100) + .Select(n => new object()) + .Select(s => s.OrDefault(f, 0.9f, mark)) + .Count(s => s is Guid g && g == mark); - mostlyMarkObjects.Should().BeGreaterThan(80); - } + mostlyMarkObjects.Should().BeGreaterThan(80); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue249.cs b/Source/Bogus.Tests/GitHubIssues/Issue249.cs index afef30f5..d1e13379 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue249.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue249.cs @@ -2,36 +2,35 @@ using System; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue249 : SeededTest { - public class Issue249 : SeededTest + public class UrlModel { - public class UrlModel - { - public string UrlTest1 { get; set; } - public string UrlTest2 { get; set; } - public string UrlTest3 { get; set; } - public string UrlTest4 { get; set; } - } + public string UrlTest1 { get; set; } + public string UrlTest2 { get; set; } + public string UrlTest3 { get; set; } + public string UrlTest4 { get; set; } + } - [Fact] - public void should_have_valid_url_for_pt_BR() - { - var FakerUrl = new Faker("pt_BR") - .RuleFor(u => u.UrlTest1, f => f.Internet.Url()) - .RuleFor(u => u.UrlTest2, f => f.Internet.Url()) - .RuleFor(u => u.UrlTest3, f => f.Internet.Url()) - .RuleFor(u => u.UrlTest4, f => f.Internet.Url()); + [Fact] + public void should_have_valid_url_for_pt_BR() + { + var FakerUrl = new Faker("pt_BR") + .RuleFor(u => u.UrlTest1, f => f.Internet.Url()) + .RuleFor(u => u.UrlTest2, f => f.Internet.Url()) + .RuleFor(u => u.UrlTest3, f => f.Internet.Url()) + .RuleFor(u => u.UrlTest4, f => f.Internet.Url()); - var x = FakerUrl.Generate(1000); + var x = FakerUrl.Generate(1000); - foreach (var u in x) - { - Uri.TryCreate(u.UrlTest1, UriKind.Absolute, out _).Should().BeTrue($"Wrong URL format: {u.UrlTest1}"); - Uri.TryCreate(u.UrlTest2, UriKind.Absolute, out _).Should().BeTrue($"Wrong URL format: {u.UrlTest2}"); - Uri.TryCreate(u.UrlTest3, UriKind.Absolute, out _).Should().BeTrue($"Wrong URL format: {u.UrlTest3}"); - Uri.TryCreate(u.UrlTest4, UriKind.Absolute, out _).Should().BeTrue($"Wrong URL format: {u.UrlTest4}"); - } + foreach (var u in x) + { + Uri.TryCreate(u.UrlTest1, UriKind.Absolute, out _).Should().BeTrue($"Wrong URL format: {u.UrlTest1}"); + Uri.TryCreate(u.UrlTest2, UriKind.Absolute, out _).Should().BeTrue($"Wrong URL format: {u.UrlTest2}"); + Uri.TryCreate(u.UrlTest3, UriKind.Absolute, out _).Should().BeTrue($"Wrong URL format: {u.UrlTest3}"); + Uri.TryCreate(u.UrlTest4, UriKind.Absolute, out _).Should().BeTrue($"Wrong URL format: {u.UrlTest4}"); } } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue253.cs b/Source/Bogus.Tests/GitHubIssues/Issue253.cs index 2d74b640..265e03a9 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue253.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue253.cs @@ -3,73 +3,72 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue253 : SeededTest { - public class Issue253 : SeededTest + [Fact] + public void can_use_advanced_namespace_rulefor_string() + { + var orderFaker = new Faker() + .RuleFor(nameof(Order.OrderId), f => f.IndexVariable++) + .RuleFor(nameof(Order.Quantity), f => f.Random.Number(1, 3)) + .RuleFor(nameof(Order.Item), f => f.Commerce.Product()); + + var order = orderFaker.Generate(); + + order.OrderId.Should().Be(0); + order.Quantity.Should().Be(2); + order.Item.Should().Be("Computer"); + } + + [Fact] + public void rulefor_a_field_that_doesnt_exist_throws() + { + var orderFaker = new Faker() + .StrictMode(true) + .RuleFor(nameof(Order.OrderId), f => f.IndexVariable++) + .RuleFor(nameof(Order.Quantity), f => f.Random.Number(1, 3)) + .RuleFor(nameof(Order.Item), f => f.Commerce.Product()); + + + Action act = () => orderFaker.RuleFor("fffff", f => f.Random.Number()); + + act.Should().Throw(); + } + + [Fact] + public void ignoring_a_field_that_doesnt_exist_throws() { - [Fact] - public void can_use_advanced_namespace_rulefor_string() - { - var orderFaker = new Faker() - .RuleFor(nameof(Order.OrderId), f => f.IndexVariable++) - .RuleFor(nameof(Order.Quantity), f => f.Random.Number(1, 3)) - .RuleFor(nameof(Order.Item), f => f.Commerce.Product()); - - var order = orderFaker.Generate(); - - order.OrderId.Should().Be(0); - order.Quantity.Should().Be(2); - order.Item.Should().Be("Computer"); - } - - [Fact] - public void rulefor_a_field_that_doesnt_exist_throws() - { - var orderFaker = new Faker() - .StrictMode(true) - .RuleFor(nameof(Order.OrderId), f => f.IndexVariable++) - .RuleFor(nameof(Order.Quantity), f => f.Random.Number(1, 3)) - .RuleFor(nameof(Order.Item), f => f.Commerce.Product()); - - - Action act = () => orderFaker.RuleFor("fffff", f => f.Random.Number()); - - act.Should().Throw(); - } - - [Fact] - public void ignoring_a_field_that_doesnt_exist_throws() - { - var orderFaker = new Faker() - .StrictMode(true) - .RuleFor(nameof(Order.OrderId), f => f.IndexVariable++) - .RuleFor(nameof(Order.Quantity), f => f.Random.Number(1, 3)) - .RuleFor(nameof(Order.Item), f => f.Commerce.Product()); - - orderFaker.Ignore(nameof(Order.Item)); - - var o = orderFaker.Generate(); - - o.Item.Should().BeNull(); - - Action act = () => orderFaker.RuleFor("hhhhh", f => f.Random.Number()); - - act.Should().Throw(); - } - - [Fact] - public void should_be_able_to_use_rulefor_with_typeT() - { - var orderFaker = new Faker() - .RuleFor(nameof(Order.OrderId), f => f.IndexVariable++) - .RuleFor(nameof(Order.Quantity), f => f.Random.Number(1, 3)) - .RuleFor(nameof(Order.Item), (f, o) => o.OrderId + f.Commerce.Product()); - - var order = orderFaker.Generate(); - - order.OrderId.Should().Be(0); - order.Quantity.Should().Be(2); - order.Item.Should().Be("0Computer"); - } + var orderFaker = new Faker() + .StrictMode(true) + .RuleFor(nameof(Order.OrderId), f => f.IndexVariable++) + .RuleFor(nameof(Order.Quantity), f => f.Random.Number(1, 3)) + .RuleFor(nameof(Order.Item), f => f.Commerce.Product()); + + orderFaker.Ignore(nameof(Order.Item)); + + var o = orderFaker.Generate(); + + o.Item.Should().BeNull(); + + Action act = () => orderFaker.RuleFor("hhhhh", f => f.Random.Number()); + + act.Should().Throw(); + } + + [Fact] + public void should_be_able_to_use_rulefor_with_typeT() + { + var orderFaker = new Faker() + .RuleFor(nameof(Order.OrderId), f => f.IndexVariable++) + .RuleFor(nameof(Order.Quantity), f => f.Random.Number(1, 3)) + .RuleFor(nameof(Order.Item), (f, o) => o.OrderId + f.Commerce.Product()); + + var order = orderFaker.Generate(); + + order.OrderId.Should().Be(0); + order.Quantity.Should().Be(2); + order.Item.Should().Be("0Computer"); } } diff --git a/Source/Bogus.Tests/GitHubIssues/Issue255.cs b/Source/Bogus.Tests/GitHubIssues/Issue255.cs index 0e17c434..47909da8 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue255.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue255.cs @@ -2,129 +2,128 @@ using System; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue255 : SeededTest { - public class Issue255 : SeededTest + private interface IParent + { + string Name { get; set; } + } + + private interface IChild : IParent + { + string City { get; set; } + } + + private class ChildWithExplicitInterface : IChild + { + string IParent.Name { get; set; } + string IChild.City { get; set; } + } + + [Fact] + public void explicit_interface_properties_in_parent_interfaces() + { + var child = new Faker() + .CustomInstantiator(f => new ChildWithExplicitInterface()) + .RuleFor(e => e.Name, f => f.Person.FullName) + .Generate(); + + child.Name.Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public void explicit_interface_properties_in_child_interfaces() + { + var child = new Faker() + .CustomInstantiator(f => new ChildWithExplicitInterface()) + .RuleFor(e => e.City, f => f.Address.City()) + .Generate(); + + child.City.Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public void explicit_interface_properties_in_child_interfaces_should_throw_when_strictmode_true() + { + var childFaker = new Faker() + .StrictMode(true) + .CustomInstantiator(f => new ChildWithExplicitInterface()) + .RuleFor(e => e.City, f => f.Address.City()); + + Action act = () => childFaker.AssertConfigurationIsValid(); + act.Should().Throw(); + } + + [Fact] + public void explicit_interface_properties_in_child_interfaces_should_throw_when_strictmode_true2() { - private interface IParent - { - string Name { get; set; } - } - - private interface IChild : IParent - { - string City { get; set; } - } - - private class ChildWithExplicitInterface : IChild - { - string IParent.Name { get; set; } - string IChild.City { get; set; } - } - - [Fact] - public void explicit_interface_properties_in_parent_interfaces() - { - var child = new Faker() - .CustomInstantiator(f => new ChildWithExplicitInterface()) - .RuleFor(e => e.Name, f => f.Person.FullName) - .Generate(); - - child.Name.Should().NotBeNullOrWhiteSpace(); - } - - [Fact] - public void explicit_interface_properties_in_child_interfaces() - { - var child = new Faker() - .CustomInstantiator(f => new ChildWithExplicitInterface()) - .RuleFor(e => e.City, f => f.Address.City()) - .Generate(); - - child.City.Should().NotBeNullOrWhiteSpace(); - } - - [Fact] - public void explicit_interface_properties_in_child_interfaces_should_throw_when_strictmode_true() - { - var childFaker = new Faker() - .StrictMode(true) - .CustomInstantiator(f => new ChildWithExplicitInterface()) - .RuleFor(e => e.City, f => f.Address.City()); - - Action act = () => childFaker.AssertConfigurationIsValid(); - act.Should().Throw(); - } - - [Fact] - public void explicit_interface_properties_in_child_interfaces_should_throw_when_strictmode_true2() - { - var childFaker = new Faker() - .StrictMode(true) - .CustomInstantiator(f => new ChildWithExplicitInterface()) - .RuleFor(e => e.Name, f => f.Address.City()); - - Action act = () => childFaker.AssertConfigurationIsValid(); - act.Should().Throw(); - } - - public class ChildWithNormalInterface : IChild - { - public string Name { get; set; } - public string City { get; set; } - } - - [Fact] - public void regular_interface_properties_in_parent() - { - var child = new Faker() - .StrictMode(true) - .CustomInstantiator(f => new ChildWithNormalInterface()) - .RuleFor(e => e.City, f => f.Address.City()) - .RuleFor(e => e.Name, f => f.Name.FirstName()) - .Generate(); - - child.City.Should().NotBeNullOrWhiteSpace(); - child.Name.Should().Be("Lupe"); - } - - private interface IParent2 - { - string Name2 { get; set; } - } - - public class ChildWithMixedInterface : IChild, IParent2 - { - public string Name { get; set; } - string IParent2.Name2 { get; set; } - string IChild.City { get; set; } - } - - [Fact] - public void strictmode_only_sees_ichild() - { - var child = new Faker() - .StrictMode(true) - .CustomInstantiator(f => new ChildWithMixedInterface()) - .RuleFor(e => e.City, f => f.Address.City()) - .RuleFor(e => e.Name, f => f.Name.FirstName()) - .Generate(); - - child.City.Should().NotBeNullOrWhiteSpace(); - child.Name.Should().Be("Lupe"); - } - - [Fact] - public void strictmode_only_sees_iparent2() - { - var child = new Faker() - .StrictMode(true) - .CustomInstantiator(f => new ChildWithMixedInterface()) - .RuleFor(e => e.Name2, f => f.Name.FirstName()) - .Generate(); - - child.Name2.Should().Be("Lee"); - } + var childFaker = new Faker() + .StrictMode(true) + .CustomInstantiator(f => new ChildWithExplicitInterface()) + .RuleFor(e => e.Name, f => f.Address.City()); + + Action act = () => childFaker.AssertConfigurationIsValid(); + act.Should().Throw(); + } + public class ChildWithNormalInterface : IChild + { + public string Name { get; set; } + public string City { get; set; } } + + [Fact] + public void regular_interface_properties_in_parent() + { + var child = new Faker() + .StrictMode(true) + .CustomInstantiator(f => new ChildWithNormalInterface()) + .RuleFor(e => e.City, f => f.Address.City()) + .RuleFor(e => e.Name, f => f.Name.FirstName()) + .Generate(); + + child.City.Should().NotBeNullOrWhiteSpace(); + child.Name.Should().Be("Lupe"); + } + + private interface IParent2 + { + string Name2 { get; set; } + } + + public class ChildWithMixedInterface : IChild, IParent2 + { + public string Name { get; set; } + string IParent2.Name2 { get; set; } + string IChild.City { get; set; } + } + + [Fact] + public void strictmode_only_sees_ichild() + { + var child = new Faker() + .StrictMode(true) + .CustomInstantiator(f => new ChildWithMixedInterface()) + .RuleFor(e => e.City, f => f.Address.City()) + .RuleFor(e => e.Name, f => f.Name.FirstName()) + .Generate(); + + child.City.Should().NotBeNullOrWhiteSpace(); + child.Name.Should().Be("Lupe"); + } + + [Fact] + public void strictmode_only_sees_iparent2() + { + var child = new Faker() + .StrictMode(true) + .CustomInstantiator(f => new ChildWithMixedInterface()) + .RuleFor(e => e.Name2, f => f.Name.FirstName()) + .Generate(); + + child.Name2.Should().Be("Lee"); + } + } diff --git a/Source/Bogus.Tests/GitHubIssues/Issue260.cs b/Source/Bogus.Tests/GitHubIssues/Issue260.cs index 0b24cc5d..b0176500 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue260.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue260.cs @@ -2,43 +2,42 @@ using Xunit; using Xunit.Abstractions; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue260 : SeededTest { - public class Issue260 : SeededTest - { - private readonly ITestOutputHelper console; + private readonly ITestOutputHelper console; - public Issue260(ITestOutputHelper console) - { - this.console = console; - } + public Issue260(ITestOutputHelper console) + { + this.console = console; + } - [Fact] - public void fast_algo3_test() - { - var r = new Randomizer(); + [Fact] + public void fast_algo3_test() + { + var r = new Randomizer(); - var x = r.Int(); + var x = r.Int(); - // the remainder of this test depends on x having a predictable value - x.Should().Be(1077349347); + // the remainder of this test depends on x having a predictable value + x.Should().Be(1077349347); - // right shift all bits except fir the first 10 bits = 2^10 = 1024. - var a = (x >> (32 - 10)) % 898; - if( a == 0 || a == 666 ) a++; + // right shift all bits except fir the first 10 bits = 2^10 = 1024. + var a = (x >> (32 - 10)) % 898; + if( a == 0 || a == 666 ) a++; - // use the first 7 bits = 2^7 = 128 - var b = (x & 0x7F); - if( b == 0 ) b++; + // use the first 7 bits = 2^7 = 128 + var b = (x & 0x7F); + if( b == 0 ) b++; - // last 2^14 = 16384, for last 4 digits of SSN - var c = (x >> 7) & 0x3FFF; - if( c >= 10000 ) c -= 10000; - if( c == 0 ) c++; + // last 2^14 = 16384, for last 4 digits of SSN + var c = (x >> 7) & 0x3FFF; + if( c >= 10000 ) c -= 10000; + if( c == 0 ) c++; - var result = $"{a:000}-{b:00}-{c:0000}"; + var result = $"{a:000}-{b:00}-{c:0000}"; - result.Should().Be("256-99-1799"); - } + result.Should().Be("256-99-1799"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue271.cs b/Source/Bogus.Tests/GitHubIssues/Issue271.cs index ed63092c..c9246087 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue271.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue271.cs @@ -2,17 +2,16 @@ using Bogus.Extensions.Brazil; using FluentAssertions; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue271 : SeededTest { - public class Issue271 : SeededTest + [Fact] + public void brazil_cpf_format_parameter_should_respect_person_context() { - [Fact] - public void brazil_cpf_format_parameter_should_respect_person_context() - { - var p = new Bogus.Person(); + var p = new Bogus.Person(); - p.Cpf().Should().Be("869.287.971-18"); - p.Cpf(includeFormatSymbols:false).Should().Be("86928797118"); - } + p.Cpf().Should().Be("869.287.971-18"); + p.Cpf(includeFormatSymbols:false).Should().Be("86928797118"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue279.cs b/Source/Bogus.Tests/GitHubIssues/Issue279.cs index 5dee35d6..7debe19b 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue279.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue279.cs @@ -11,282 +11,280 @@ using Xunit; using Z.ExtensionMethods; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue279 : SeededTest { - public class Issue279 : SeededTest + public class Bar { - public class Bar - { - public string Prop1 { get; set; } - public string Prop2 { get; set; } - public string Prop3 { get; set; } - } + public string Prop1 { get; set; } + public string Prop2 { get; set; } + public string Prop3 { get; set; } + } - [Fact] - public void last_rule_defined_for_a_property_wins() - { - var barFaker = new Faker() - .RuleFor(b => b.Prop1, f => - { - return "aaaa" + 1; - }) - .RuleFor(b => b.Prop3, f => - { - return "bbbb" + 2; - }) - .RuleFor(b => b.Prop1, f => - { - return "cccc" + 3; - }) - .RuleFor(b => b.Prop2, f => - { - return "cccc" + 4; - }) - .RuleFor(b => b.Prop1, f => - { - return "bbbb" + 5; // executed 1 - }) - .RuleFor(b => b.Prop2, f => - { - return "aaaa" + 6; - }) - .RuleFor(b => b.Prop3, f => - { - return "aaaa" + 7; - }) - .RuleFor(b => b.Prop2, f => - { - return "bbbb" + 8; // executed 3 - }) - .RuleFor(b => b.Prop3, f => - { - return "cccc" + 9; // executed 2 - }) - ; - - var bar = barFaker.Generate(); - bar.Prop1.Should().Be("bbbb5"); - bar.Prop2.Should().Be("bbbb8"); - bar.Prop3.Should().Be("cccc9"); - } + [Fact] + public void last_rule_defined_for_a_property_wins() + { + var barFaker = new Faker() + .RuleFor(b => b.Prop1, f => + { + return "aaaa" + 1; + }) + .RuleFor(b => b.Prop3, f => + { + return "bbbb" + 2; + }) + .RuleFor(b => b.Prop1, f => + { + return "cccc" + 3; + }) + .RuleFor(b => b.Prop2, f => + { + return "cccc" + 4; + }) + .RuleFor(b => b.Prop1, f => + { + return "bbbb" + 5; // executed 1 + }) + .RuleFor(b => b.Prop2, f => + { + return "aaaa" + 6; + }) + .RuleFor(b => b.Prop3, f => + { + return "aaaa" + 7; + }) + .RuleFor(b => b.Prop2, f => + { + return "bbbb" + 8; // executed 3 + }) + .RuleFor(b => b.Prop3, f => + { + return "cccc" + 9; // executed 2 + }) + ; + + var bar = barFaker.Generate(); + bar.Prop1.Should().Be("bbbb5"); + bar.Prop2.Should().Be("bbbb8"); + bar.Prop3.Should().Be("cccc9"); + } - [Fact] - public void modifying_rules_from_initial_order_can_affect_other_initial_rules_too() - { - var barFaker = new Faker() + [Fact] + public void modifying_rules_from_initial_order_can_affect_other_initial_rules_too() + { + var barFaker = new Faker() + .RuleFor(b => b.Prop1, f => f.Company.CompanyName()) + .RuleFor(b => b.Prop2, f => f.Commerce.Product()) + .RuleFor(b => b.Prop3, (f, b) => "Prop3 depends on Prop1: " + b.Prop1); + + var bar1 = barFaker.Generate(); + + bar1.Should().NotBeNull(); + bar1.Prop1.Should().Be("Brekke - Schultz"); + bar1.Prop2.Should().Be("Tuna"); + bar1.Prop3.Should().EndWith(bar1.Prop1); + + //reconfigure + barFaker + .RuleFor(b => b.Prop1, f => "Reconfigured Prop1 Value."); + + var bar2 = barFaker.Generate(); + bar2.Should().NotBeNull(); + bar2.Prop1.Should().Be("Reconfigured Prop1 Value."); + bar2.Prop2.Should().Be("Chair"); + bar2.Prop3.Should().EndWith(bar2.Prop1); + } + + [Fact] + public void redefine_ordering_other_than_initial_order_of_faker_t_rules_throws_by_default() + { + var barFaker = new Faker() .RuleFor(b => b.Prop1, f => f.Company.CompanyName()) .RuleFor(b => b.Prop2, f => f.Commerce.Product()) .RuleFor(b => b.Prop3, (f, b) => "Prop3 depends on Prop1: " + b.Prop1); - var bar1 = barFaker.Generate(); - - bar1.Should().NotBeNull(); - bar1.Prop1.Should().Be("Brekke - Schultz"); - bar1.Prop2.Should().Be("Tuna"); - bar1.Prop3.Should().EndWith(bar1.Prop1); - - //reconfigure - barFaker - .RuleFor(b => b.Prop1, f => "Reconfigured Prop1 Value."); + var bar1 = barFaker.Generate(); - var bar2 = barFaker.Generate(); - bar2.Should().NotBeNull(); - bar2.Prop1.Should().Be("Reconfigured Prop1 Value."); - bar2.Prop2.Should().Be("Chair"); - bar2.Prop3.Should().EndWith(bar2.Prop1); - } + bar1.Should().NotBeNull(); + bar1.Prop1.Should().Be("Brekke - Schultz"); + bar1.Prop2.Should().Be("Tuna"); + bar1.Prop3.Should().EndWith(bar1.Prop1); - [Fact] - public void redefine_ordering_other_than_initial_order_of_faker_t_rules_throws_by_default() - { - var barFaker = new Faker() - .RuleFor(b => b.Prop1, f => f.Company.CompanyName()) - .RuleFor(b => b.Prop2, f => f.Commerce.Product()) - .RuleFor(b => b.Prop3, (f, b) => "Prop3 depends on Prop1: " + b.Prop1); + //reconfigure + barFaker + .RuleFor(b => b.Prop2, f => f.Company.CompanyName() + " zzz") + .RuleFor(b => b.Prop1, (f, b) => ReverseString(b.Prop2)); - var bar1 = barFaker.Generate(); + //The current (and expected) behavior of Faker throws an exception + //due to developer trying to re-order the execution from the initially + //defined order. + Action generate = () => barFaker.Generate(); - bar1.Should().NotBeNull(); - bar1.Prop1.Should().Be("Brekke - Schultz"); - bar1.Prop2.Should().Be("Tuna"); - bar1.Prop3.Should().EndWith(bar1.Prop1); + generate.Should().Throw(); + } - //reconfigure - barFaker - .RuleFor(b => b.Prop2, f => f.Company.CompanyName() + " zzz") - .RuleFor(b => b.Prop1, (f, b) => ReverseString(b.Prop2)); + [Fact] + public void allow_redefine_ordering_of_faker_t_rules_using_derived_faker_t() + { + var barFaker = new ReorderFaker() + .RuleFor(b => b.Prop1, f => f.Company.CompanyName()) + .RuleFor(b => b.Prop2, f => f.Commerce.Product()) + .RuleFor(b => b.Prop3, (f, b) => "Prop3 depends on Prop1: "+ b.Prop1) + as ReorderFaker; + + var bar1 = barFaker.Generate(); + + bar1.Should().NotBeNull(); + bar1.Prop1.Should().Be("Brekke - Schultz"); + bar1.Prop2.Should().Be("Tuna"); + bar1.Prop3.Should().EndWith(bar1.Prop1); + + //reconfigure + barFaker.Reorder() + .RuleFor(b => b.Prop2, f => f.Company.CompanyName() + " zzz") + .RuleFor(b => b.Prop1, (f, b) => ReverseString(b.Prop2)); + + var bar2 = barFaker.Generate(); + + bar2.Should().NotBeNull(); + bar2.Prop1.Should().Be("zzz cnI relluM"); + bar2.Prop2.Should().Be("Muller Inc zzz"); + bar2.Prop3.Should().EndWith(bar2.Prop1); + } - //The current (and expected) behavior of Faker throws an exception - //due to developer trying to re-order the execution from the initially - //defined order. - Action generate = () => barFaker.Generate(); + private string ReverseString(string value) + { + return value.Reverse(); + } - generate.Should().Throw(); - } + public class ReorderFaker : Faker where T : class + { + private Dictionary reorderActions = new Dictionary(); - [Fact] - public void allow_redefine_ordering_of_faker_t_rules_using_derived_faker_t() - { - var barFaker = new ReorderFaker() - .RuleFor(b => b.Prop1, f => f.Company.CompanyName()) - .RuleFor(b => b.Prop2, f => f.Commerce.Product()) - .RuleFor(b => b.Prop3, (f, b) => "Prop3 depends on Prop1: "+ b.Prop1) - as ReorderFaker; - - var bar1 = barFaker.Generate(); - - bar1.Should().NotBeNull(); - bar1.Prop1.Should().Be("Brekke - Schultz"); - bar1.Prop2.Should().Be("Tuna"); - bar1.Prop3.Should().EndWith(bar1.Prop1); - - //reconfigure - barFaker.Reorder() - .RuleFor(b => b.Prop2, f => f.Company.CompanyName() + " zzz") - .RuleFor(b => b.Prop1, (f, b) => ReverseString(b.Prop2)); - - var bar2 = barFaker.Generate(); - - bar2.Should().NotBeNull(); - bar2.Prop1.Should().Be("zzz cnI relluM"); - bar2.Prop2.Should().Be("Muller Inc zzz"); - bar2.Prop3.Should().EndWith(bar2.Prop1); - } + private MultiDictionary> initialRules; - private string ReverseString(string value) + private bool loaded = false; + public ReorderFaker Reorder() { - return value.Reverse(); + //save the very fist initial order, then faker is locked down by the initial order. + this.initialRules ??= this.Actions.Clone(); + this.reorderActions.Clear(); + this.loaded = false; + return this; } - public class ReorderFaker : Faker where T : class + protected override Faker AddRule(string propertyOrField, Func invoker) { - private Dictionary reorderActions = new Dictionary(); - - private MultiDictionary> initialRules; - - private bool loaded = false; - public ReorderFaker Reorder() + if (initialRules is null) { - //save the very fist initial order, then faker is locked down by the initial order. - this.initialRules ??= this.Actions.Clone(); - this.reorderActions.Clear(); - this.loaded = false; + base.AddRule(propertyOrField, invoker); return this; } - protected override Faker AddRule(string propertyOrField, Func invoker) - { - if (initialRules is null) + var rule = new PopulateAction { - base.AddRule(propertyOrField, invoker); - return this; - } + Action = invoker, + RuleSet = currentRuleSet, + PropertyName = propertyOrField, + }; - var rule = new PopulateAction - { - Action = invoker, - RuleSet = currentRuleSet, - PropertyName = propertyOrField, - }; + if ( reorderActions.TryGetValue(currentRuleSet, out var currentActions) && + currentActions.Contains(propertyOrField)) + { + currentActions.Remove(propertyOrField); + } - if ( reorderActions.TryGetValue(currentRuleSet, out var currentActions) && - currentActions.Contains(propertyOrField)) - { - currentActions.Remove(propertyOrField); - } + AddOrderedRule(reorderActions, currentRuleSet, propertyOrField, rule); - AddOrderedRule(reorderActions, currentRuleSet, propertyOrField, rule); + return this; + } - return this; + public static void AddOrderedRule(Dictionary ruleSets, string currentRuleSet, string propertyOrField, PopulateAction populateAction) + { + if (ruleSets.TryGetValue(currentRuleSet, out var currentActions)) + { + currentActions.Add(propertyOrField, populateAction); } + else + { + var newActionSet = new OrderedDictionary + { + {propertyOrField, populateAction} + }; + ruleSets.Add(currentRuleSet, newActionSet); + } + } - public static void AddOrderedRule(Dictionary ruleSets, string currentRuleSet, string propertyOrField, PopulateAction populateAction) + protected override void PopulateInternal(T instance, string[] ruleSets) + { + if( !loaded && this.initialRules != null ) { - if (ruleSets.TryGetValue(currentRuleSet, out var currentActions)) - { - currentActions.Add(propertyOrField, populateAction); - } - else - { - var newActionSet = new OrderedDictionary - { - {propertyOrField, populateAction} - }; - ruleSets.Add(currentRuleSet, newActionSet); - } + LoadRulesInNewOrder(); + this.loaded = true; } - protected override void PopulateInternal(T instance, string[] ruleSets) + base.PopulateInternal(instance, ruleSets); + } + + public ReorderFaker LoadRulesInNewOrder() + { + this.Actions.Clear(); + + //use our new rules first. + foreach( var ruleSet in reorderActions ) { - if( !loaded && this.initialRules != null ) + var ruleSetName = ruleSet.Key; + var orderedActions = ruleSet.Value; + + //first our ordered rules. + foreach( PopulateAction newRule in orderedActions.Values ) { - LoadRulesInNewOrder(); - this.loaded = true; + this.Actions.Add(ruleSetName, newRule.PropertyName, newRule); } - - base.PopulateInternal(instance, ruleSets); } - public ReorderFaker LoadRulesInNewOrder() + //then the initial rules. + foreach( var initialRuleSet in this.initialRules ) { - this.Actions.Clear(); + //but add the initial rule only if it doesn't exist. + var initialRuleSetName = initialRuleSet.Key; + var initialActions = initialRuleSet.Value; - //use our new rules first. - foreach( var ruleSet in reorderActions ) + foreach( var initialRule in initialActions.Values ) { - var ruleSetName = ruleSet.Key; - var orderedActions = ruleSet.Value; - - //first our ordered rules. - foreach( PopulateAction newRule in orderedActions.Values ) + if( this.Actions.TryGetValue(initialRuleSetName, out var existingRules) && + existingRules.ContainsKey(initialRule.PropertyName) ) { - this.Actions.Add(ruleSetName, newRule.PropertyName, newRule); + continue; } - } - //then the initial rules. - foreach( var initialRuleSet in this.initialRules ) - { - //but add the initial rule only if it doesn't exist. - var initialRuleSetName = initialRuleSet.Key; - var initialActions = initialRuleSet.Value; - - foreach( var initialRule in initialActions.Values ) - { - if( this.Actions.TryGetValue(initialRuleSetName, out var existingRules) && - existingRules.ContainsKey(initialRule.PropertyName) ) - { - continue; - } - - this.Actions.Add(initialRuleSetName, initialRule.PropertyName, initialRule); - } + this.Actions.Add(initialRuleSetName, initialRule.PropertyName, initialRule); } - - return this; } + return this; } } - public static class ExtensionsForMultiDictionary +} + +public static class ExtensionsForMultiDictionary +{ + public static MultiDictionary Clone(this MultiDictionary source) { - public static MultiDictionary Clone(this MultiDictionary source) - { - var target = new MultiDictionary(source.Comparer); + var target = new MultiDictionary(source.Comparer); - foreach( var level1 in source ) + foreach( var level1 in source ) + { + foreach( var level2 in level1.Value ) { - foreach( var level2 in level1.Value ) - { - target.Add(level1.Key, level2.Key, level2.Value); - } + target.Add(level1.Key, level2.Key, level2.Value); } - - return target; } - } + return target; + } } diff --git a/Source/Bogus.Tests/GitHubIssues/Issue280.cs b/Source/Bogus.Tests/GitHubIssues/Issue280.cs index 3f117f40..50ce0a06 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue280.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue280.cs @@ -4,91 +4,90 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue280 : SeededTest { - public class Issue280 : SeededTest + public class Foo { - public class Foo - { - public string Baz; - public int Bar; - public ushort Boo; - } + public string Baz; + public int Bar; + public ushort Boo; + } - [Fact] - public void automatic_type_conversion_fails_by_default() - { - var fooFaker = new Faker() - .RuleFor(o => o.Baz, f => f.Hacker.Phrase()) - .RuleFor(o => o.Bar, f => f.PickRandom(10, 20, 30)) - .RuleFor(o => o.Boo, f => f.PickRandom(40, 50, 60)); + [Fact] + public void automatic_type_conversion_fails_by_default() + { + var fooFaker = new Faker() + .RuleFor(o => o.Baz, f => f.Hacker.Phrase()) + .RuleFor(o => o.Bar, f => f.PickRandom(10, 20, 30)) + .RuleFor(o => o.Boo, f => f.PickRandom(40, 50, 60)); - Action generate = () => fooFaker.Generate(); + Action generate = () => fooFaker.Generate(); - generate.Should().Throw(); - } + generate.Should().Throw(); + } - [Fact] - public void custom_faker_with_automatic_conversion_does_not_throw() - { - var fooFaker = new MagicFaker() - .RuleFor(o => o.Baz, f => f.Hacker.Phrase()) - .RuleFor(o => o.Bar, f => f.PickRandom(10, 20, 30)) - .RuleFor(o => o.Boo, f => f.PickRandom(40, 50, 60)); + [Fact] + public void custom_faker_with_automatic_conversion_does_not_throw() + { + var fooFaker = new MagicFaker() + .RuleFor(o => o.Baz, f => f.Hacker.Phrase()) + .RuleFor(o => o.Bar, f => f.PickRandom(10, 20, 30)) + .RuleFor(o => o.Boo, f => f.PickRandom(40, 50, 60)); - var foo = fooFaker.Generate(); + var foo = fooFaker.Generate(); - foo.Baz.Should().Be("Use the neural RAM driver, then you can calculate the neural driver!"); - foo.Bar.Should().Be(10); - foo.Boo.Should().Be(60); - } + foo.Baz.Should().Be("Use the neural RAM driver, then you can calculate the neural driver!"); + foo.Bar.Should().Be(10); + foo.Boo.Should().Be(60); + } - public class MagicFaker : Faker where T : class + public class MagicFaker : Faker where T : class + { + protected override Faker AddRule(string propertyOrField, Func invoker) { - protected override Faker AddRule(string propertyOrField, Func invoker) - { - Func hook = (faker, t) => - { - var initialValue = invoker(faker, t); - return ConvertValue(propertyOrField, initialValue); - }; - return base.AddRule(propertyOrField, hook); - } + Func hook = (faker, t) => + { + var initialValue = invoker(faker, t); + return ConvertValue(propertyOrField, initialValue); + }; + return base.AddRule(propertyOrField, hook); + } - private object ConvertValue(string propertyOrField, object initialValue) - { - if( initialValue is null ) return null; + private object ConvertValue(string propertyOrField, object initialValue) + { + if( initialValue is null ) return null; - if( !this.TypeProperties.TryGetValue(propertyOrField, out var memberInfo) ) - return initialValue; + if( !this.TypeProperties.TryGetValue(propertyOrField, out var memberInfo) ) + return initialValue; - var targetType = memberInfo switch - { - PropertyInfo pi => pi.PropertyType, - FieldInfo fi => fi.FieldType, - _ => throw new Exception("Unknown reflection type.") - }; + var targetType = memberInfo switch + { + PropertyInfo pi => pi.PropertyType, + FieldInfo fi => fi.FieldType, + _ => throw new Exception("Unknown reflection type.") + }; - var convertedValue = targetType switch - { - Type t when t == typeof(int) => Convert.ToInt32(initialValue), - Type t when t == typeof(uint) => Convert.ToUInt32(initialValue), - Type t when t == typeof(long) => Convert.ToInt64(initialValue), - Type t when t == typeof(ulong) => Convert.ToUInt64(initialValue), - Type t when t == typeof(short) => Convert.ToInt16(initialValue), - Type t when t == typeof(ushort) => Convert.ToUInt16(initialValue), - Type t when t == typeof(float) => Convert.ToSingle(initialValue), - Type t when t == typeof(double) => Convert.ToDouble(initialValue), - Type t when t == typeof(decimal) => Convert.ToDecimal(initialValue), - Type t when t == typeof(byte) => Convert.ToByte(initialValue), - Type t when t == typeof(sbyte) => Convert.ToSByte(initialValue), - Type t when t == typeof(bool) => Convert.ToBoolean(initialValue), - Type t when t == typeof(char) => Convert.ToChar(initialValue), - _ => initialValue - }; + var convertedValue = targetType switch + { + Type t when t == typeof(int) => Convert.ToInt32(initialValue), + Type t when t == typeof(uint) => Convert.ToUInt32(initialValue), + Type t when t == typeof(long) => Convert.ToInt64(initialValue), + Type t when t == typeof(ulong) => Convert.ToUInt64(initialValue), + Type t when t == typeof(short) => Convert.ToInt16(initialValue), + Type t when t == typeof(ushort) => Convert.ToUInt16(initialValue), + Type t when t == typeof(float) => Convert.ToSingle(initialValue), + Type t when t == typeof(double) => Convert.ToDouble(initialValue), + Type t when t == typeof(decimal) => Convert.ToDecimal(initialValue), + Type t when t == typeof(byte) => Convert.ToByte(initialValue), + Type t when t == typeof(sbyte) => Convert.ToSByte(initialValue), + Type t when t == typeof(bool) => Convert.ToBoolean(initialValue), + Type t when t == typeof(char) => Convert.ToChar(initialValue), + _ => initialValue + }; - return convertedValue; - } + return convertedValue; } } } diff --git a/Source/Bogus.Tests/GitHubIssues/Issue309.cs b/Source/Bogus.Tests/GitHubIssues/Issue309.cs index 1c00f99a..5e7a6993 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue309.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue309.cs @@ -5,76 +5,75 @@ using Xunit; using Xunit.Abstractions; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue309 : SeededTest { - public class Issue309 : SeededTest - { - private readonly ITestOutputHelper console; + private readonly ITestOutputHelper console; - public Issue309(ITestOutputHelper console) - { - this.console = console; - } + public Issue309(ITestOutputHelper console) + { + this.console = console; + } - [Fact] - public void ruleforlist_addrange() - { - var hobbyFaker = new Faker() - .RuleFor(h => h.Id, f => f.IndexFaker) - .RuleFor(h => h.Text, f => f.Random.Word()); + [Fact] + public void ruleforlist_addrange() + { + var hobbyFaker = new Faker() + .RuleFor(h => h.Id, f => f.IndexFaker) + .RuleFor(h => h.Text, f => f.Random.Word()); - var userFaker = new Faker() - .RuleFor(u => u.Id, f => f.IndexFaker) - .RuleFor(u => u.Name, f => f.Name.FirstName()) - .RuleForList(u => u.Hobbies, f => hobbyFaker.Generate(3)); + var userFaker = new Faker() + .RuleFor(u => u.Id, f => f.IndexFaker) + .RuleFor(u => u.Name, f => f.Name.FirstName()) + .RuleForList(u => u.Hobbies, f => hobbyFaker.Generate(3)); - var user = userFaker.Generate(); - user.Should().NotBeNull(); + var user = userFaker.Generate(); + user.Should().NotBeNull(); - var expected = new[] - { - new Hobby {Id = 0, Text = "Soft"}, - new Hobby {Id = 1, Text = "deposit"}, - new Hobby {Id = 2, Text = "Checking Account"} - }; + var expected = new[] + { + new Hobby {Id = 0, Text = "Soft"}, + new Hobby {Id = 1, Text = "deposit"}, + new Hobby {Id = 2, Text = "Checking Account"} + }; - console.Dump(user); - user.Hobbies.Should().HaveCount(3); - user.Hobbies.Should().BeEquivalentTo(expected, opt => opt.WithStrictOrdering()); - } + console.Dump(user); + user.Hobbies.Should().HaveCount(3); + user.Hobbies.Should().BeEquivalentTo(expected, opt => opt.WithStrictOrdering()); + } - public class Hobby - { - public int Id { get; set; } - public string Text { get; set; } - } - public class User - { - public int Id { get; set; } - public string Name { get; set; } - public List Hobbies { get; } = new List(); - } + public class Hobby + { + public int Id { get; set; } + public string Text { get; set; } } + public class User + { + public int Id { get; set; } + public string Name { get; set; } + public List Hobbies { get; } = new List(); + } +} - public static class ExtensionsForIssue309 +public static class ExtensionsForIssue309 +{ + public static Faker RuleForList(this Faker fakerT, Expression>> propertyOfListU, Func> itemsGetter) + where T : class { - public static Faker RuleForList(this Faker fakerT, Expression>> propertyOfListU, Func> itemsGetter) - where T : class - { - var func = propertyOfListU.Compile(); + var func = propertyOfListU.Compile(); - fakerT.RuleFor(propertyOfListU, (f, t) => - { + fakerT.RuleFor(propertyOfListU, (f, t) => + { - var list = func(t); - var items = itemsGetter(f); + var list = func(t); + var items = itemsGetter(f); - list.AddRange(items); + list.AddRange(items); - return items; - }); + return items; + }); - return fakerT; - } + return fakerT; } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue313.cs b/Source/Bogus.Tests/GitHubIssues/Issue313.cs index a216bbbd..0e6cd25d 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue313.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue313.cs @@ -2,25 +2,23 @@ using Bogus.Extensions.Extras; using FluentAssertions; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue313 : SeededTest { - public class Issue313 : SeededTest + [Fact] + public void can_create_custom_credit_card_number_PAN() { - [Fact] - public void can_create_custom_credit_card_number_PAN() - { - var f = new Faker(); - Visa16Digit(f).Should() - .HaveLength(16) - .And - .Be("4618606064391758"); - } - - public static string Visa16Digit(Faker f) - { - const string format = "4##############"; - return f.Random.ReplaceNumbers(format).AppendCheckDigit(); - } + var f = new Faker(); + Visa16Digit(f).Should() + .HaveLength(16) + .And + .Be("4618606064391758"); } + public static string Visa16Digit(Faker f) + { + const string format = "4##############"; + return f.Random.ReplaceNumbers(format).AppendCheckDigit(); + } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue318.cs b/Source/Bogus.Tests/GitHubIssues/Issue318.cs index a534de17..ea91d306 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue318.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue318.cs @@ -2,24 +2,23 @@ using Bogus.Extensions.UnitedKingdom; using FluentAssertions; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue318 : SeededTest { - public class Issue318 : SeededTest + [Fact] + public void can_get_country_of_uk() { - [Fact] - public void can_get_country_of_uk() - { - var f = new Faker("en_GB"); - var country = f.Address.CountryOfUnitedKingdom(); - country.Should().Be("Wales"); - } + var f = new Faker("en_GB"); + var country = f.Address.CountryOfUnitedKingdom(); + country.Should().Be("Wales"); + } - [Fact] - public void can_get_country_of_uk_without_locale_specified() - { - var f = new Faker(); - var country = f.Address.CountryOfUnitedKingdom(); - country.Should().Be("Wales"); - } + [Fact] + public void can_get_country_of_uk_without_locale_specified() + { + var f = new Faker(); + var country = f.Address.CountryOfUnitedKingdom(); + country.Should().Be("Wales"); } } diff --git a/Source/Bogus.Tests/GitHubIssues/Issue319.cs b/Source/Bogus.Tests/GitHubIssues/Issue319.cs index 19adf40c..21c39ba5 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue319.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue319.cs @@ -3,35 +3,34 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue319 : SeededTest { - public class Issue319 : SeededTest + [Fact] + public void can_generate_decimal_edge_case() { - [Fact] - public void can_generate_decimal_edge_case() - { - var r = new Randomizer(); + var r = new Randomizer(); - Action a = () => - { - r.Decimal(0m, decimal.MaxValue); - r.Decimal(0m, decimal.MaxValue); - r.Decimal(0m, decimal.MaxValue); - r.Decimal(0m, decimal.MaxValue); - }; - a.Should().NotThrow(); - } + Action a = () => + { + r.Decimal(0m, decimal.MaxValue); + r.Decimal(0m, decimal.MaxValue); + r.Decimal(0m, decimal.MaxValue); + r.Decimal(0m, decimal.MaxValue); + }; + a.Should().NotThrow(); + } - [Fact] - public void decimal2_should_throw_on_edge_case() - { - var r = new Randomizer(); - Action a = () => - { - r.Decimal2(0, decimal.MaxValue); - }; + [Fact] + public void decimal2_should_throw_on_edge_case() + { + var r = new Randomizer(); + Action a = () => + { + r.Decimal2(0, decimal.MaxValue); + }; - a.Should().Throw(); - } + a.Should().Throw(); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue321.cs b/Source/Bogus.Tests/GitHubIssues/Issue321.cs index 62cdeb18..d70c82f2 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue321.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue321.cs @@ -3,123 +3,122 @@ using Bogus.Extensions; using Xunit.Abstractions; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue321 : SeededTest { - public class Issue321 : SeededTest + private readonly ITestOutputHelper console; + + public Issue321(ITestOutputHelper console) { - private readonly ITestOutputHelper console; + this.console = console; + } - public Issue321(ITestOutputHelper console) - { - this.console = console; - } + [Fact] + public void reuse_data_from_custom_instantiator() + { + var unions = new[] + { + new Union("Married"), + new Union("Single"), + new Union("Divorced"), + }; - [Fact] - public void reuse_data_from_custom_instantiator() - { - var unions = new[] + var memberFaker = new Faker() + .CustomInstantiator(f => { - new Union("Married"), - new Union("Single"), - new Union("Divorced"), - }; - - var memberFaker = new Faker() - .CustomInstantiator(f => - { - //Store intermediate state here. - var email = f.Internet.ExampleEmail(); - var selectedUnion = f.PickRandom(unions); - - return new Member( - f.Random.Guid().ToString("N"), - f.Name.FullName(), - f.Date.Between(new DateTime(1950, 3, 9), new DateTime(2010, 4, 2)), - f.Address.FullAddress(), - f.Phone.PhoneNumber(), - email, - CreateAppUser(email).Id, - selectedUnion, - selectedUnion.Id, - f.Random.ReplaceNumbers("######"), - f.Rant.Random.Words(5) - ); - }); - - var testMembers = memberFaker.GenerateBetween(4, 10); - console.Dump(testMembers); - } + //Store intermediate state here. + var email = f.Internet.ExampleEmail(); + var selectedUnion = f.PickRandom(unions); - private AppUser CreateAppUser(string email) + return new Member( + f.Random.Guid().ToString("N"), + f.Name.FullName(), + f.Date.Between(new DateTime(1950, 3, 9), new DateTime(2010, 4, 2)), + f.Address.FullAddress(), + f.Phone.PhoneNumber(), + email, + CreateAppUser(email).Id, + selectedUnion, + selectedUnion.Id, + f.Random.ReplaceNumbers("######"), + f.Rant.Random.Words(5) + ); + }); + + var testMembers = memberFaker.GenerateBetween(4, 10); + console.Dump(testMembers); + } + + private AppUser CreateAppUser(string email) + { + return new AppUser(email); + } + + public class AppUser + { + public AppUser(string email) { - return new AppUser(email); + this.Email = email; + this.Id = $"appuser_id:{this.Email.ToLower()}"; } - public class AppUser - { - public AppUser(string email) - { - this.Email = email; - this.Id = $"appuser_id:{this.Email.ToLower()}"; - } + public string Email { get; set; } - public string Email { get; set; } + public string Id { get; set; } + } - public string Id { get; set; } + public class Union + { + public Union(string description) + { + this.Description = description; + this.Id = $"union_id:{this.Description.ToLower()}"; } - public class Union - { - public Union(string description) - { - this.Description = description; - this.Id = $"union_id:{this.Description.ToLower()}"; - } + public string Description { get; set; } - public string Description { get; set; } + public string Id { get; set; } + } - public string Id { get; set; } - } + public class Member + { + public string Id { get; } + public string Name { get; } + public DateTime Dob { get; } + public string Address { get; } + public string Phone { get; } + public string Email { get; } + public string AppUserId { get; } + public Union Union { get; } + public string UnionId { get; } + public string Code { get; } + public string Description { get; } - public class Member + public Member( + string id, + string name, + DateTime dob, + string address, + string phone, + string email, + string appUserId, + Union union, + string unionId, + string code, + string description) { - public string Id { get; } - public string Name { get; } - public DateTime Dob { get; } - public string Address { get; } - public string Phone { get; } - public string Email { get; } - public string AppUserId { get; } - public Union Union { get; } - public string UnionId { get; } - public string Code { get; } - public string Description { get; } - - public Member( - string id, - string name, - DateTime dob, - string address, - string phone, - string email, - string appUserId, - Union union, - string unionId, - string code, - string description) - { - this.Id = id; - this.Name = name; - this.Dob = dob; - this.Address = address; - this.Phone = phone; - this.Email = email; - this.AppUserId = appUserId; - this.Union = union; - this.UnionId = unionId; - this.Code = code; - this.Description = description; - } + this.Id = id; + this.Name = name; + this.Dob = dob; + this.Address = address; + this.Phone = phone; + this.Email = email; + this.AppUserId = appUserId; + this.Union = union; + this.UnionId = unionId; + this.Code = code; + this.Description = description; } } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue328.cs b/Source/Bogus.Tests/GitHubIssues/Issue328.cs index 14812858..20b49cbe 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue328.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue328.cs @@ -3,20 +3,19 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue328 : SeededTest { - public class Issue328 : SeededTest + [Fact] + public void can_use_pt_br_locale_address_city_without_exception_thrown() { - [Fact] - public void can_use_pt_br_locale_address_city_without_exception_thrown() - { - var a = new Address("pt_BR"); - Action act = () => a.City(); + var a = new Address("pt_BR"); + Action act = () => a.City(); - act.Should().NotThrow(); + act.Should().NotThrow(); - a.CityPrefix().Should().BeEmpty(because: "Current locale for pt_BR.address.city_prefix is empty. If it's not empty, then the data_extend/pt_BR.address.city name formats should be removed."); - a.CitySuffix().Should().BeEmpty(because: "Current locale for pt_BR.address.city_suffix is empty. If it's not empty, then the data_extend/pt_BR.address.city name formats should be removed."); - } + a.CityPrefix().Should().BeEmpty(because: "Current locale for pt_BR.address.city_prefix is empty. If it's not empty, then the data_extend/pt_BR.address.city name formats should be removed."); + a.CitySuffix().Should().BeEmpty(because: "Current locale for pt_BR.address.city_suffix is empty. If it's not empty, then the data_extend/pt_BR.address.city name formats should be removed."); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue342.cs b/Source/Bogus.Tests/GitHubIssues/Issue342.cs index 2770ca75..74e4a2e8 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue342.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue342.cs @@ -3,15 +3,14 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue342 : SeededTest { - public class Issue342 : SeededTest + [Fact] + public void more_realistic_pt_BR_city_name() { - [Fact] - public void more_realistic_pt_BR_city_name() - { - var a = new Address("pt_BR"); - a.City().Should().Be("Pelotas"); - } + var a = new Address("pt_BR"); + a.City().Should().Be("Pelotas"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue355.cs b/Source/Bogus.Tests/GitHubIssues/Issue355.cs index 8aa8bcd4..0ea7c381 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue355.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue355.cs @@ -2,15 +2,14 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue355 : SeededTest { - public class Issue355 : SeededTest + [Fact] + public void pt_BR_has_gendered_names() { - [Fact] - public void pt_BR_has_gendered_names() - { - var n = new Name("pt_BR"); - n.SupportsGenderFirstNames.Should().BeTrue(); - } + var n = new Name("pt_BR"); + n.SupportsGenderFirstNames.Should().BeTrue(); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue389.cs b/Source/Bogus.Tests/GitHubIssues/Issue389.cs index fa84392b..9079f933 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue389.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue389.cs @@ -1,49 +1,48 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue389 { - public class Issue389 + [Fact] + public void property_with_private_setter_in_base_class_is_assigned() + { + var foo = new Faker() + .RuleFor(f => f.PropInFoo, _ => 42) + .RuleFor(f => f.PropInFooBase, _ => 123) + .Generate(); + + foo.PropInFoo.Should().Be(42); + foo.PropInFooBase.Should().Be(123); + } + + public class FooBase + { + public int PropInFooBase { get; private set; } + } + + public class Foo : FooBase { - [Fact] - public void property_with_private_setter_in_base_class_is_assigned() - { - var foo = new Faker() - .RuleFor(f => f.PropInFoo, _ => 42) - .RuleFor(f => f.PropInFooBase, _ => 123) - .Generate(); - - foo.PropInFoo.Should().Be(42); - foo.PropInFooBase.Should().Be(123); - } - - public class FooBase - { - public int PropInFooBase { get; private set; } - } - - public class Foo : FooBase - { - public int PropInFoo { get; private set; } - } - - public class Zoo : Foo - { - public int PropInZoo { get; private set; } - } - - [Fact] - public void property_with_private_setter_inheritance_chain_is_assigned() - { - var zoo = new Faker() - .RuleFor(f => f.PropInFoo, _ => 42) - .RuleFor(f => f.PropInFooBase, _ => 123) - .RuleFor(f => f.PropInZoo, _ => 77) - .Generate(); - - zoo.PropInFoo.Should().Be(42); - zoo.PropInFooBase.Should().Be(123); - zoo.PropInZoo.Should().Be(77); - } + public int PropInFoo { get; private set; } + } + + public class Zoo : Foo + { + public int PropInZoo { get; private set; } + } + + [Fact] + public void property_with_private_setter_inheritance_chain_is_assigned() + { + var zoo = new Faker() + .RuleFor(f => f.PropInFoo, _ => 42) + .RuleFor(f => f.PropInFooBase, _ => 123) + .RuleFor(f => f.PropInZoo, _ => 77) + .Generate(); + + zoo.PropInFoo.Should().Be(42); + zoo.PropInFooBase.Should().Be(123); + zoo.PropInZoo.Should().Be(77); } } diff --git a/Source/Bogus.Tests/GitHubIssues/Issue411.cs b/Source/Bogus.Tests/GitHubIssues/Issue411.cs index 6ae2551f..0b619991 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue411.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue411.cs @@ -3,50 +3,49 @@ using Xunit; using FluentAssertions; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue411 { - public class Issue411 + [Fact] + public void randomizer_uses_custom_PRNG() { - [Fact] - public void randomizer_uses_custom_PRNG() - { - var customRandomizer = new CustomRandomizer(); + var customRandomizer = new CustomRandomizer(); - for (int i = 0; i < 10; i++) - { - var index = i % CustomRandom.Data.Count; - var knownValue = CustomRandom.Data[index]; + for (int i = 0; i < 10; i++) + { + var index = i % CustomRandom.Data.Count; + var knownValue = CustomRandom.Data[index]; - customRandomizer.Number(int.MaxValue).Should().Be(knownValue); - } + customRandomizer.Number(int.MaxValue).Should().Be(knownValue); } + } - private class CustomRandom : Random - { - public static readonly List Data = new List { 4, 3, 9, 2001, 42, 7, 13 }; - private int index = 0; + private class CustomRandom : Random + { + public static readonly List Data = new List { 4, 3, 9, 2001, 42, 7, 13 }; + private int index = 0; - public override int Next() + public override int Next() + { + if (index >= Data.Count) { - if (index >= Data.Count) - { - index = 0; - } - - return Data[index++]; + index = 0; } - public override int Next(int minValue, int maxValue) => Next() % (maxValue - minValue) + minValue; - public override void NextBytes(byte[] buffer) => throw new NotImplementedException(); - public override double NextDouble() => throw new NotImplementedException(); + return Data[index++]; } - private class CustomRandomizer : Randomizer + public override int Next(int minValue, int maxValue) => Next() % (maxValue - minValue) + minValue; + public override void NextBytes(byte[] buffer) => throw new NotImplementedException(); + public override double NextDouble() => throw new NotImplementedException(); + } + + private class CustomRandomizer : Randomizer + { + public CustomRandomizer() { - public CustomRandomizer() - { - localSeed = new CustomRandom(); - } + localSeed = new CustomRandom(); } } } diff --git a/Source/Bogus.Tests/GitHubIssues/Issue45.cs b/Source/Bogus.Tests/GitHubIssues/Issue45.cs index 9f59e1ff..c0fa5270 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue45.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue45.cs @@ -3,37 +3,36 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue45 : SeededTest { - public class Issue45 : SeededTest + public class Issue45Object { - public class Issue45Object - { - public int Id { get; set; } - public List Phones { get; set; } // PROBLEM !!! - } + public int Id { get; set; } + public List Phones { get; set; } // PROBLEM !!! + } - [Fact] - public void issue_45_better_fluency() - { - var ids = 0; + [Fact] + public void issue_45_better_fluency() + { + var ids = 0; - var test = new Faker() - .RuleFor(p => p.Id, f => ids++) - .RuleFor(p => p.Phones, f => f.Make(5, () => f.Phone.PhoneNumber())); + var test = new Faker() + .RuleFor(p => p.Id, f => ids++) + .RuleFor(p => p.Phones, f => f.Make(5, () => f.Phone.PhoneNumber())); - test.Generate(1).First().Phones.Count.Should().Be(5); - } + test.Generate(1).First().Phones.Count.Should().Be(5); + } - [Fact] - public void with_int_argument() - { - var test = new Faker() - .RuleFor(p => p.Id, f => f.IndexVariable++) - .RuleFor(p => p.Phones, f => f.Make(5, i => i.ToString())); + [Fact] + public void with_int_argument() + { + var test = new Faker() + .RuleFor(p => p.Id, f => f.IndexVariable++) + .RuleFor(p => p.Phones, f => f.Make(5, i => i.ToString())); - test.Generate(1).First().Phones.Select(int.Parse) - .Distinct().Should().Equal(1, 2, 3, 4, 5); - } + test.Generate(1).First().Phones.Select(int.Parse) + .Distinct().Should().Equal(1, 2, 3, 4, 5); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue48.cs b/Source/Bogus.Tests/GitHubIssues/Issue48.cs index b3dd1da1..522ddc2b 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue48.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue48.cs @@ -3,48 +3,47 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue48 : SeededTest { - public class Issue48 : SeededTest + [Fact] + public void issue_48() + { + Faker clients = new Faker() + .RuleFor(x => x.Description, y => y.Lorem.Paragraphs(1)); + var users = new List(); + + users.AddRange( + new Faker() + .RuleFor(x => x.Name, y => + { + var i = y.IndexFaker; + i.Dump(); + return new[] {"John", "Mary", "Mike", "Tom"}[i % 4]; + }) + .RuleFor(x => x.Email, (y, x) => $"{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) + ); + + users.Dump(); + + + users.Select(f => f.Name).ToList().Should().Equal("John", "Mary", "Mike", "Tom"); + } + + public class User + { + public string Name { get; set; } + public string Email { get; set; } + public Client Client { get; set; } + public string UserName { get; set; } + } + + public class Client { - [Fact] - public void issue_48() - { - Faker clients = new Faker() - .RuleFor(x => x.Description, y => y.Lorem.Paragraphs(1)); - var users = new List(); - - users.AddRange( - new Faker() - .RuleFor(x => x.Name, y => - { - var i = y.IndexFaker; - i.Dump(); - return new[] {"John", "Mary", "Mike", "Tom"}[i % 4]; - }) - .RuleFor(x => x.Email, (y, x) => $"{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) - ); - - users.Dump(); - - - users.Select(f => f.Name).ToList().Should().Equal("John", "Mary", "Mike", "Tom"); - } - - public class User - { - public string Name { get; set; } - public string Email { get; set; } - public Client Client { get; set; } - public string UserName { get; set; } - } - - public class Client - { - public string Description { get; set; } - } + public string Description { get; set; } } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue49.cs b/Source/Bogus.Tests/GitHubIssues/Issue49.cs index 1ed9e790..2a4c4dc9 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue49.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue49.cs @@ -3,28 +3,27 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue49 : SeededTest { - public class Issue49 : SeededTest + [Fact] + public void issue_49_pr_51_pick_random_subset() { - [Fact] - public void issue_49_pr_51_pick_random_subset() - { - var items = Enumerable.Range(1, 10).ToArray(); + var items = Enumerable.Range(1, 10).ToArray(); - var f = new Faker(); + var f = new Faker(); - Action bounds1 = () => { f.PickRandom(items, 25).ToList(); }; + Action bounds1 = () => { f.PickRandom(items, 25).ToList(); }; - bounds1.Should().Throw(); + bounds1.Should().Throw(); - Action bounds2 = () => { f.PickRandom(items, -1).ToList(); }; + Action bounds2 = () => { f.PickRandom(items, -1).ToList(); }; - bounds2.Should().Throw(); + bounds2.Should().Throw(); - var picked = f.PickRandom(items, 4).ToArray(); - picked.Dump(); - picked.Should().Equal(7, 2, 9, 8); - } + var picked = f.PickRandom(items, 4).ToArray(); + picked.Dump(); + picked.Should().Equal(7, 2, 9, 8); } } diff --git a/Source/Bogus.Tests/GitHubIssues/Issue55.cs b/Source/Bogus.Tests/GitHubIssues/Issue55.cs index de38535c..5b6d0707 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue55.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue55.cs @@ -4,103 +4,101 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue55 : SeededTest { - public class Issue55 : SeededTest + public class DerivedFaker : Faker { - public class DerivedFaker : Faker + public DerivedFaker() { - public DerivedFaker() - { - this.RuleFor(o => o.Code, f => f.Random.AlphaNumeric(5)); - this.RuleFor(o => o.Dba, f => f.Company.CompanyName()); - } - - public override List Generate(int count, string ruleSets = null) - { - var list = base.Generate(count, ruleSets) - .OrderBy(o => o.Code) - .ToList(); - list[0].Primary = true; - return list; - } + this.RuleFor(o => o.Code, f => f.Random.AlphaNumeric(5)); + this.RuleFor(o => o.Dba, f => f.Company.CompanyName()); } - [Fact] - public void issue_55_collection_finish_with_syntax() + public override List Generate(int count, string ruleSets = null) { - var derivedFaker = new DerivedFaker(); - - var fakes = derivedFaker.Generate(5); + var list = base.Generate(count, ruleSets) + .OrderBy(o => o.Code) + .ToList(); + list[0].Primary = true; + return list; } + } - public class Bar - { - public string Code { get; set; } - public string Dba { get; set; } - public bool Primary { get; set; } - } + [Fact] + public void issue_55_collection_finish_with_syntax() + { + var derivedFaker = new DerivedFaker(); + + var fakes = derivedFaker.Generate(5); + } + + public class Bar + { + public string Code { get; set; } + public string Dba { get; set; } + public bool Primary { get; set; } + } #if NETCOREAPP3_1 - [Fact] - public void with_range_and_index_syntax() - { - var faker = new Faker() - .RuleFor(o => o.Code, f => f.Random.AlphaNumeric(5)) - .RuleFor(o => o.Dba, f => f.Company.CompanyName()); + [Fact] + public void with_range_and_index_syntax() + { + var faker = new Faker() + .RuleFor(o => o.Code, f => f.Random.AlphaNumeric(5)) + .RuleFor(o => o.Dba, f => f.Company.CompanyName()); - //set the first item to primary. - var bars = faker.Generate(5).ToArray(); - bars[0].Apply(b => b.Primary = true); - bars[0].Primary.Should().BeTrue(); - bars[1..5].Select(b => b.Primary).Should().OnlyContain(x => x == false); + //set the first item to primary. + var bars = faker.Generate(5).ToArray(); + bars[0].Apply(b => b.Primary = true); + bars[0].Primary.Should().BeTrue(); + bars[1..5].Select(b => b.Primary).Should().OnlyContain(x => x == false); - //set the last item to primary. - bars = faker.Generate(5).ToArray(); - bars[^1].Apply(b => b.Primary = true); - bars.Last().Primary.Should().BeTrue(); + //set the last item to primary. + bars = faker.Generate(5).ToArray(); + bars[^1].Apply(b => b.Primary = true); + bars.Last().Primary.Should().BeTrue(); - //set all items to primary - bars = faker.Generate(5).ToArray(); - bars[..].Apply(b => b.Primary = true); - bars[..].Select(b => b.Primary).Should().OnlyContain(x => x == true); + //set all items to primary + bars = faker.Generate(5).ToArray(); + bars[..].Apply(b => b.Primary = true); + bars[..].Select(b => b.Primary).Should().OnlyContain(x => x == true); - //set only the first 3 - bars = faker.Generate(5).ToArray(); - bars[..3].Apply(b => b.Primary = true); - bars.Select(b => b.Primary).Should().Equal(true, true, true, false, false); - } + //set only the first 3 + bars = faker.Generate(5).ToArray(); + bars[..3].Apply(b => b.Primary = true); + bars.Select(b => b.Primary).Should().Equal(true, true, true, false, false); + } #endif - } +} #if NETCOREAPP3_1 - public static class ExtensionsForCollection +public static class ExtensionsForCollection +{ + public static T Apply(this T item, Action applyAction) + { + applyAction(item); + return item; + } + + public static T[] Apply(this T[] array, Action applyAction) { - public static T Apply(this T item, Action applyAction) + foreach( var item in array ) { applyAction(item); - return item; } - - public static T[] Apply(this T[] array, Action applyAction) + return array; + } + public static IEnumerable Apply(this IEnumerable sequence, Action applyAction) + { + foreach( var item in sequence ) { - foreach( var item in array ) - { - applyAction(item); - } - return array; + applyAction(item); } - public static IEnumerable Apply(this IEnumerable sequence, Action applyAction) - { - foreach( var item in sequence ) - { - applyAction(item); - } - return sequence; - } + return sequence; } +} #endif - -} \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue61.cs b/Source/Bogus.Tests/GitHubIssues/Issue61.cs index c2bcaa21..e75c555d 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue61.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue61.cs @@ -1,32 +1,31 @@ using Xunit; using static Bogus.Tests.GitHubIssues.Issue61.HashIdExtension; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue61 : SeededTest { - public class Issue61 : SeededTest + public static class HashIdExtension { - public static class HashIdExtension - { - public static Hashids Hashid { get; set; } - } + public static Hashids Hashid { get; set; } + } - [Fact] - public void can_have_custom_hashid_extension() - { - //Custom - Hashid = new Hashids(alphabet: "~!@#$%.&*()_+-=;<>"); + [Fact] + public void can_have_custom_hashid_extension() + { + //Custom + Hashid = new Hashids(alphabet: "~!@#$%.&*()_+-=;<>"); - var faker = new Faker() - .RuleFor(o => o.Id, f => Hashid.Encode(f.Random.Digits(3))) - .RuleFor(o => o.TrackingNumber, f => f.Random.Number(3)); + var faker = new Faker() + .RuleFor(o => o.Id, f => Hashid.Encode(f.Random.Digits(3))) + .RuleFor(o => o.TrackingNumber, f => f.Random.Number(3)); - faker.Generate(5).Dump(); - } + faker.Generate(5).Dump(); + } - public class SomeUser - { - public string Id { get; set; } - public int TrackingNumber { get; set; } - } + public class SomeUser + { + public string Id { get; set; } + public int TrackingNumber { get; set; } } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue70.cs b/Source/Bogus.Tests/GitHubIssues/Issue70.cs index ed56ca0d..82686bb8 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue70.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue70.cs @@ -1,74 +1,73 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +//https://github.com/bchavez/Bogus/issues/70 +public class Issue70 : SeededTest { - //https://github.com/bchavez/Bogus/issues/70 - public class Issue70 : SeededTest + [Fact] + public void should_be_able_to_create_derived_faker_with_class_hierarchy() { - [Fact] - public void should_be_able_to_create_derived_faker_with_class_hierarchy() - { - var baseBFaker = new Faker() - .RuleFor(b => b.Value, f => f.Random.Int(1, 5)); + var baseBFaker = new Faker() + .RuleFor(b => b.Value, f => f.Random.Int(1, 5)); - var derivedBFaker = new Faker() - .RuleFor(b => b.Value, f => f.Random.Int(6, 10)); + var derivedBFaker = new Faker() + .RuleFor(b => b.Value, f => f.Random.Int(6, 10)); - //Works - var baseAFaker = new Faker() - .RuleFor(a => a.SomeProp, () => baseBFaker.Generate()); - ; + //Works + var baseAFaker = new Faker() + .RuleFor(a => a.SomeProp, () => baseBFaker.Generate()); + ; - //Threw System.ArgumentException: 'An item with the same key has already been added.' - var derivedAFaker = new Faker() - .RuleFor(da => da.SomeProp, () => derivedBFaker.Generate()); + //Threw System.ArgumentException: 'An item with the same key has already been added.' + var derivedAFaker = new Faker() + .RuleFor(da => da.SomeProp, () => derivedBFaker.Generate()); - DerivedA derivedA = derivedAFaker.Generate(); + DerivedA derivedA = derivedAFaker.Generate(); - derivedA.SomeProp.Value.Should().BeInRange(6, 10); - BaseA baseA = derivedA; - baseA.SomeProp.Should().BeNull(); - } + derivedA.SomeProp.Value.Should().BeInRange(6, 10); + BaseA baseA = derivedA; + baseA.SomeProp.Should().BeNull(); + } - [Fact] - public void quick_test_for_derivedC() - { - var fakerC = new Faker() - .RuleFor(c => c.Value2, f => f.Random.Int(1, 10)) - .RuleFor(c => c.Value, f => f.Random.Int(11, 20)); + [Fact] + public void quick_test_for_derivedC() + { + var fakerC = new Faker() + .RuleFor(c => c.Value2, f => f.Random.Int(1, 10)) + .RuleFor(c => c.Value, f => f.Random.Int(11, 20)); - ClassC fakeC = fakerC; + ClassC fakeC = fakerC; - fakeC.Value2.Should().BeInRange(1, 10); - fakeC.Value.Should().BeInRange(11, 20); - } + fakeC.Value2.Should().BeInRange(1, 10); + fakeC.Value.Should().BeInRange(11, 20); } +} - class BaseA - { - public BaseB SomeProp { get; set; } - } +class BaseA +{ + public BaseB SomeProp { get; set; } +} - class DerivedA : BaseA - { - public new DerivedB SomeProp { get; set; } - } +class DerivedA : BaseA +{ + public new DerivedB SomeProp { get; set; } +} - class BaseB - { - public int Value { get; set; } - } +class BaseB +{ + public int Value { get; set; } +} - class DerivedB : BaseB - { - public new int Value { get; set; } - } +class DerivedB : BaseB +{ + public new int Value { get; set; } +} - class ClassC : BaseB - { - public int Value2 { get; set; } - } +class ClassC : BaseB +{ + public int Value2 { get; set; } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue86.cs b/Source/Bogus.Tests/GitHubIssues/Issue86.cs index 641be360..03d126a6 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue86.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue86.cs @@ -3,33 +3,32 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class Issue86 : SeededTest { - public class Issue86 : SeededTest - { - private Internet internet; + private Internet internet; - public Issue86() - { - internet = new Internet(); - } + public Issue86() + { + internet = new Internet(); + } - [Fact] - public void should_remove_diacritic_marks() - { - "hello world".RemoveDiacritics().Should().Be("hello AOUi world"); - } + [Fact] + public void should_remove_diacritic_marks() + { + "hello world".RemoveDiacritics().Should().Be("hello AOUi world"); + } - [Fact] - public void should_remove_diacritic_marks_in_email() - { - internet.Email("ra'in", "chavez").Should().Be("ssrainAeOeUei81@yahoo.com"); - } + [Fact] + public void should_remove_diacritic_marks_in_email() + { + internet.Email("ra'in", "chavez").Should().Be("ssrainAeOeUei81@yahoo.com"); + } - [Fact] - public void should_remove_diacritic_marks_in_username() - { - internet.UserName("ri'an", "chaez").Should().Be("ssriAeOeUeian.chaAeOeUeiez"); - } + [Fact] + public void should_remove_diacritic_marks_in_username() + { + internet.UserName("ri'an", "chaez").Should().Be("ssriAeOeUeian.chaAeOeUeiez"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue93.cs b/Source/Bogus.Tests/GitHubIssues/Issue93.cs index a51a7c37..70bcea7a 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue93.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue93.cs @@ -2,36 +2,35 @@ using Xunit; using Xunit.Abstractions; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +//https://github.com/bchavez/Bogus/issues/93 +public class Issue93 : SeededTest { - //https://github.com/bchavez/Bogus/issues/93 - public class Issue93 : SeededTest - { - private readonly ITestOutputHelper console; + private readonly ITestOutputHelper console; - public Issue93(ITestOutputHelper console) - { - this.console = console; - } + public Issue93(ITestOutputHelper console) + { + this.console = console; + } - [Fact] - public void should_be_able_to_use_list_of_objects_and_pick_random() - { - var myObjFaker = new Faker() - .RuleFor(m => m.SomeString, f => f.Lorem.Sentence()); + [Fact] + public void should_be_able_to_use_list_of_objects_and_pick_random() + { + var myObjFaker = new Faker() + .RuleFor(m => m.SomeString, f => f.Lorem.Sentence()); - var objects = myObjFaker.Generate(20); + var objects = myObjFaker.Generate(20); - var faker = new Faker(); - var picked = faker.PickRandom(objects); + var faker = new Faker(); + var picked = faker.PickRandom(objects); - console.WriteLine(picked.DumpString()); - picked.GetType().Should().Be(); - } + console.WriteLine(picked.DumpString()); + picked.GetType().Should().Be(); + } - class MyObj - { - public string SomeString { get; set; } - } + class MyObj + { + public string SomeString { get; set; } } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/Issue99.cs b/Source/Bogus.Tests/GitHubIssues/Issue99.cs index 35658514..e7153dfc 100644 --- a/Source/Bogus.Tests/GitHubIssues/Issue99.cs +++ b/Source/Bogus.Tests/GitHubIssues/Issue99.cs @@ -2,16 +2,15 @@ using Bogus.DataSets; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +//https://github.com/bchavez/Bogus/issues/99 +public class Issue99 : SeededTest { - //https://github.com/bchavez/Bogus/issues/99 - public class Issue99 : SeededTest + [Fact] + public void multi_threaded_locale_access_should_be_okay() { - [Fact] - public void multi_threaded_locale_access_should_be_okay() - { - ParallelEnumerable.Range(0, 9999) - .Select(i => new Name("nl")).ToList(); - } + ParallelEnumerable.Range(0, 9999) + .Select(i => new Name("nl")).ToList(); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/PullRequest113.cs b/Source/Bogus.Tests/GitHubIssues/PullRequest113.cs index ce2d2c3f..6e2eb019 100644 --- a/Source/Bogus.Tests/GitHubIssues/PullRequest113.cs +++ b/Source/Bogus.Tests/GitHubIssues/PullRequest113.cs @@ -3,16 +3,15 @@ using Xunit; using static Bogus.DataSets.LoremPixelCategory; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class PullRequest113 : SeededTest { - public class PullRequest113 : SeededTest + [Fact] + public void category_exists_in_image_url() { - [Fact] - public void category_exists_in_image_url() - { - var images = new Images(); + var images = new Images(); - images.LoremPixelUrl(Cats).Should().Contain("cat"); - } + images.LoremPixelUrl(Cats).Should().Contain("cat"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/PullRequest149.cs b/Source/Bogus.Tests/GitHubIssues/PullRequest149.cs index 4fe03b9a..dfbd98a4 100644 --- a/Source/Bogus.Tests/GitHubIssues/PullRequest149.cs +++ b/Source/Bogus.Tests/GitHubIssues/PullRequest149.cs @@ -2,16 +2,15 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class PullRequest149 : SeededTest { - public class PullRequest149 : SeededTest + [Fact] + public void ensure_arabic_locale_exists() { - [Fact] - public void ensure_arabic_locale_exists() - { - Action a = () => new Faker("ar"); + Action a = () => new Faker("ar"); - a.Should().NotThrow(); - } + a.Should().NotThrow(); } } diff --git a/Source/Bogus.Tests/GitHubIssues/PullRequest180.cs b/Source/Bogus.Tests/GitHubIssues/PullRequest180.cs index 6bc63157..cbdccf4d 100644 --- a/Source/Bogus.Tests/GitHubIssues/PullRequest180.cs +++ b/Source/Bogus.Tests/GitHubIssues/PullRequest180.cs @@ -4,29 +4,28 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class PullRequest180 : SeededTest, IDisposable { - public class PullRequest180 : SeededTest, IDisposable - { - private CultureInfo current; + private CultureInfo current; - public PullRequest180() - { - current = Thread.CurrentThread.CurrentCulture; - } + public PullRequest180() + { + current = Thread.CurrentThread.CurrentCulture; + } - [Fact] - public void lower_invarant_should_be_used_to_avoid_locale_issues_in_json_path() - { - var turkish = CultureInfo.GetCultureInfo("tr"); - Thread.CurrentThread.CurrentCulture = turkish; - var faker = new Faker("tr"); - faker.Internet.Url().Should().NotBeNullOrWhiteSpace(); - } + [Fact] + public void lower_invarant_should_be_used_to_avoid_locale_issues_in_json_path() + { + var turkish = CultureInfo.GetCultureInfo("tr"); + Thread.CurrentThread.CurrentCulture = turkish; + var faker = new Faker("tr"); + faker.Internet.Url().Should().NotBeNullOrWhiteSpace(); + } - public void Dispose() - { - Thread.CurrentThread.CurrentCulture = current; - } + public void Dispose() + { + Thread.CurrentThread.CurrentCulture = current; } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/PullRequest194.cs b/Source/Bogus.Tests/GitHubIssues/PullRequest194.cs index ecc987b6..8a31ebe5 100644 --- a/Source/Bogus.Tests/GitHubIssues/PullRequest194.cs +++ b/Source/Bogus.Tests/GitHubIssues/PullRequest194.cs @@ -1,37 +1,36 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class PullRequest194 : SeededTest { - public class PullRequest194 : SeededTest + [Fact] + public void can_generate_nl_locale_with_modifications() { - [Fact] - public void can_generate_nl_locale_with_modifications() - { - var f = new Faker("nl"); + var f = new Faker("nl"); - f.Address.StreetSuffix().Should().Be("sloot"); - f.Company.Suffixes().Should().Equal( - new[] - { - "Bank", - "BV", - "B.V.", - "NV", - "N.V.", - "V.O.F.", - "International", - "Groep", - "Group", - "HRM", - "ICT", - "IT", - "Maatschappij", - "Online", - "en Zonen" - }); + f.Address.StreetSuffix().Should().Be("sloot"); + f.Company.Suffixes().Should().Equal( + new[] + { + "Bank", + "BV", + "B.V.", + "NV", + "N.V.", + "V.O.F.", + "International", + "Groep", + "Group", + "HRM", + "ICT", + "IT", + "Maatschappij", + "Online", + "en Zonen" + }); - f.Name.FirstName().Should().Be("Bram"); - } + f.Name.FirstName().Should().Be("Bram"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/PullRequest197.cs b/Source/Bogus.Tests/GitHubIssues/PullRequest197.cs index f7b3d548..38191f83 100644 --- a/Source/Bogus.Tests/GitHubIssues/PullRequest197.cs +++ b/Source/Bogus.Tests/GitHubIssues/PullRequest197.cs @@ -2,25 +2,24 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class PullRequest197 : SeededTest { - public class PullRequest197 : SeededTest + public class Internet2 : Internet { - public class Internet2 : Internet - { - public Name DependentDataSet => this.Name; - } + public Name DependentDataSet => this.Name; + } - [Fact] - public void ensure_randomizer_propagates_to_dependent_datasets() - { - var internet = new Internet2(); + [Fact] + public void ensure_randomizer_propagates_to_dependent_datasets() + { + var internet = new Internet2(); - var internetRandomizer = internet.Random; + var internetRandomizer = internet.Random; - var dependentRandomizer = internet.DependentDataSet.Random; + var dependentRandomizer = internet.DependentDataSet.Random; - dependentRandomizer.Should().BeSameAs(internetRandomizer); - } + dependentRandomizer.Should().BeSameAs(internetRandomizer); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/PullRequest258.cs b/Source/Bogus.Tests/GitHubIssues/PullRequest258.cs index 43b719ee..1f31e363 100644 --- a/Source/Bogus.Tests/GitHubIssues/PullRequest258.cs +++ b/Source/Bogus.Tests/GitHubIssues/PullRequest258.cs @@ -2,31 +2,30 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class PullRequest258 : SeededTest { - public class PullRequest258 : SeededTest + [Fact] + public void can_get_rooted_url_path_with_fileExt() { - [Fact] - public void can_get_rooted_url_path_with_fileExt() - { - var i = new Internet(); + var i = new Internet(); - i.UrlRootedPath(".txt").Should().Be("/soft/deposit.txt"); - } + i.UrlRootedPath(".txt").Should().Be("/soft/deposit.txt"); + } - [Fact] - public void get_rooted_path_with_no_ext() - { - var i = new Internet(); + [Fact] + public void get_rooted_path_with_no_ext() + { + var i = new Internet(); - i.UrlRootedPath().Should().Be("/soft/deposit"); - } + i.UrlRootedPath().Should().Be("/soft/deposit"); + } - [Fact] - public void check_UrlWithPath_fileExt_parameter() - { - var i = new Internet(); - i.UrlWithPath(fileExt: ".mp3").Should().Be("https://ambrose.net/soft/deposit.mp3"); - } + [Fact] + public void check_UrlWithPath_fileExt_parameter() + { + var i = new Internet(); + i.UrlWithPath(fileExt: ".mp3").Should().Be("https://ambrose.net/soft/deposit.mp3"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/PullRequest259.cs b/Source/Bogus.Tests/GitHubIssues/PullRequest259.cs index cf7b923a..a01e6d46 100644 --- a/Source/Bogus.Tests/GitHubIssues/PullRequest259.cs +++ b/Source/Bogus.Tests/GitHubIssues/PullRequest259.cs @@ -3,48 +3,47 @@ using Xunit; using static Bogus.Tests.GitHubIssues.PullRequest259.DrinkRuleSets; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class PullRequest259 : SeededTest { - public class PullRequest259 : SeededTest + class Drink { - class Drink - { - public string Name { get; set; } - public int FluidOunce { get; set; } - } + public string Name { get; set; } + public int FluidOunce { get; set; } + } - public static class DrinkRuleSets - { - public const string Cherry = nameof(Cherry); - public const string Lemonade = nameof(Lemonade); - public const string SmallDrink = nameof(SmallDrink); - public const string LargeDrink = nameof(LargeDrink); - } + public static class DrinkRuleSets + { + public const string Cherry = nameof(Cherry); + public const string Lemonade = nameof(Lemonade); + public const string SmallDrink = nameof(SmallDrink); + public const string LargeDrink = nameof(LargeDrink); + } - [Fact] - public void ensure_generate_forever_applies_ruleset() - { - var drinkFaker = new Faker() - .RuleSet(Cherry, set => - { - set.RuleFor(d => d.Name, f => "cherry coke"); - }) - .RuleSet(Lemonade, set => + [Fact] + public void ensure_generate_forever_applies_ruleset() + { + var drinkFaker = new Faker() + .RuleSet(Cherry, set => { - set.RuleFor(d => d.Name, f => "strawberry lemonade"); + set.RuleFor(d => d.Name, f => "cherry coke"); }) - .RuleSet(SmallDrink, set => - { - set.RuleFor(d => d.FluidOunce, f => 12); - }); + .RuleSet(Lemonade, set => + { + set.RuleFor(d => d.Name, f => "strawberry lemonade"); + }) + .RuleSet(SmallDrink, set => + { + set.RuleFor(d => d.FluidOunce, f => 12); + }); - var cherryDrink = drinkFaker.GenerateForever($"{Cherry}, {SmallDrink}").First(); - cherryDrink.Name.Should().Be("cherry coke"); - cherryDrink.FluidOunce.Should().Be(12); + var cherryDrink = drinkFaker.GenerateForever($"{Cherry}, {SmallDrink}").First(); + cherryDrink.Name.Should().Be("cherry coke"); + cherryDrink.FluidOunce.Should().Be(12); - var lemonadeDrink = drinkFaker.GenerateForever(Lemonade).First(); - lemonadeDrink.Name.Should().Be("strawberry lemonade"); - lemonadeDrink.FluidOunce.Should().Be(0); - } + var lemonadeDrink = drinkFaker.GenerateForever(Lemonade).First(); + lemonadeDrink.Name.Should().Be("strawberry lemonade"); + lemonadeDrink.FluidOunce.Should().Be(0); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/PullRequest261.cs b/Source/Bogus.Tests/GitHubIssues/PullRequest261.cs index c72fc49c..408aca6e 100644 --- a/Source/Bogus.Tests/GitHubIssues/PullRequest261.cs +++ b/Source/Bogus.Tests/GitHubIssues/PullRequest261.cs @@ -3,31 +3,30 @@ using Xunit; using Xunit.Abstractions; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class PullRequest261 : SeededTest { - public class PullRequest261 : SeededTest - { - private readonly ITestOutputHelper console; + private readonly ITestOutputHelper console; - public PullRequest261(ITestOutputHelper console) - { - this.console = console; - } + public PullRequest261(ITestOutputHelper console) + { + this.console = console; + } - [Fact] - public void can_generate_ipv4_endpoint() - { - var i = new Internet(); - var ep = i.IpEndPoint(); - ep.ToString().Should().Be("218.35.156.76:2333"); - } + [Fact] + public void can_generate_ipv4_endpoint() + { + var i = new Internet(); + var ep = i.IpEndPoint(); + ep.ToString().Should().Be("218.35.156.76:2333"); + } - [Fact] - public void can_generate_ipv6_endpoint() - { - var i = new Internet(); - var ep = i.Ipv6EndPoint(); - ep.ToString().Should().Be("[da23:9c4c:e0c4:2dd7:e3c4:a896:17f2:55b2]:45956"); - } + [Fact] + public void can_generate_ipv6_endpoint() + { + var i = new Internet(); + var ep = i.Ipv6EndPoint(); + ep.ToString().Should().Be("[da23:9c4c:e0c4:2dd7:e3c4:a896:17f2:55b2]:45956"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/GitHubIssues/PullRequest513.cs b/Source/Bogus.Tests/GitHubIssues/PullRequest513.cs index 0157891d..894f33b3 100644 --- a/Source/Bogus.Tests/GitHubIssues/PullRequest513.cs +++ b/Source/Bogus.Tests/GitHubIssues/PullRequest513.cs @@ -2,15 +2,14 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.GitHubIssues +namespace Bogus.Tests.GitHubIssues; + +public class PullRequest513 : SeededTest { - public class PullRequest513 : SeededTest + [Fact] + public void sv_has_gendered_names() { - [Fact] - public void sv_has_gendered_names() - { - var n = new Name("sv"); - n.SupportsGenderFirstNames.Should().BeTrue(); - } + var n = new Name("sv"); + n.SupportsGenderFirstNames.Should().BeTrue(); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/HandleBarTests.cs b/Source/Bogus.Tests/HandleBarTests.cs index 9ecb23b8..9b1d5719 100644 --- a/Source/Bogus.Tests/HandleBarTests.cs +++ b/Source/Bogus.Tests/HandleBarTests.cs @@ -2,25 +2,24 @@ using Xunit; using Xunit.Abstractions; -namespace Bogus.Tests +namespace Bogus.Tests; + +public class HandleBarTests : SeededTest { - public class HandleBarTests : SeededTest - { - private readonly ITestOutputHelper console; + private readonly ITestOutputHelper console; - public HandleBarTests(ITestOutputHelper console) - { - this.console = console; - } + public HandleBarTests(ITestOutputHelper console) + { + this.console = console; + } - [Fact] - public void parse_test() - { - var f = new Faker(); - var s = Tokenizer.Parse("{{name.lastName}}, {{name.firstName}} {{name.suffix}}", f.Name); + [Fact] + public void parse_test() + { + var f = new Faker(); + var s = Tokenizer.Parse("{{name.lastName}}, {{name.firstName}} {{name.suffix}}", f.Name); - console.Dump(s); - s.Should().Be("Mitchell, Bernhard DDS"); - } + console.Dump(s); + s.Should().Be("Mitchell, Bernhard DDS"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/HandlebarsTests/ArgumentsTest.cs b/Source/Bogus.Tests/HandlebarsTests/ArgumentsTest.cs index 7a100942..90e7b11c 100644 --- a/Source/Bogus.Tests/HandlebarsTests/ArgumentsTest.cs +++ b/Source/Bogus.Tests/HandlebarsTests/ArgumentsTest.cs @@ -3,139 +3,138 @@ using Xunit; using Xunit.Abstractions; -namespace Bogus.Tests.HandlebarsTests +namespace Bogus.Tests.HandlebarsTests; + +public class ArgumentsTest : SeededTest { - public class ArgumentsTest : SeededTest - { - private readonly ITestOutputHelper console; - - public ArgumentsTest(ITestOutputHelper console) - { - this.console = console; - } - - - [Fact] - public void can_parse_random_number_request_without_arguments() - { - var faker = new Faker(); - var result = faker.Parse("{{randomizer.number}}"); - int.Parse(result); - } - - [Fact] - public void can_parse_random_bool_request_without_arguments() - { - var faker = new Faker(); - var result = faker.Parse("{{randomizer.bool}}"); - bool.Parse(result); - } - - - [Fact] - public void can_parse_random_number_parameterized_request() - { - var faker = new Faker(); - var result = faker.Parse("{{randomizer.number (100)}}"); - int.Parse(result).Should().Be(60); - } - - [Fact] - public void can_parse_random_number_parameterized_request_overload() - { - var faker = new Faker(); - var result = faker.Parse("{{randomizer.number (50, 100)}}"); - int.Parse(result).Should().Be(80); - } - - [Fact] - public void cant_parse_random_number_parameterized_request_incorrect_overload() - { - var faker = new Faker(); - Assert.Throws(() => faker.Parse("{{randomizer.number (50, 100, 1000)}}")); - } - - [Fact] - public void cant_parse_random_number_parameterized_request_incorrect_type() - { - var faker = new Faker(); - Assert.Throws(() => faker.Parse("{{randomizer.number (a)}}")); - } - - [Fact] - public void cant_parse_random_string_request_with_not_enough_arguments() - { - var faker = new Faker(); - Assert.Throws(() => faker.Parse("{{randomizer.ReplaceNumbers}}")); - } - - [Fact] - public void can_parse_random_string_request_with_enough_arguments() - { - var faker = new Faker(); - faker.Parse("{{randomizer.string (5, 10)}}") - .Length.Should() - .BeGreaterOrEqualTo(5) - .And - .BeLessOrEqualTo(10); - } - - [Fact] - public void can_parse_random_string_request_with_full_arguments() - { - var faker = new Faker(); - faker.Parse("{{randomizer.string (5, 10, a, z)}}").Should().Be("cvqaqbrm"); - } - - [Fact] - public void can_parse_enum_argument() - { - var faker = new Faker(); - faker.Parse("{{name.firstname(Female)}} {{name.firstname(Male)}}").Should().Be("Lindsay Jonathan"); - } - - [Fact] - public void can_parse_string_argument() - { - var faker = new Faker(); - faker.Parse(@"{{randomizer.string2(9, wxyz)}}").Should().Be("ywzywywyx"); - } - - [Fact] - public void can_parse_bool_argument() - { - var faker = new Faker(); - faker.Parse(@"{{randomizer.hash(5, true)}}").Should().Be("91DA0"); - } - - [Fact] - public void can_parse_datetime_with_arguments() - { - var faker = new Faker(); - var dtString = faker.Parse("{{date.between(2015-10-04, 2017-11-03) }}"); - var dt = DateTimeOffset.Parse(dtString); - dt.Should() - .BeAfter(new DateTime(2015, 10, 04)) - .And - .BeBefore(new DateTime(2017, 11, 03)); - } - - [Fact] - public void unmached_brace_should_throw() - { - var faker = new Faker(); - //easy to miss the closing ) with }} handle bars. - Action a = () => faker.Parse("{{randomizer.number(100 }}"); - a.Should().Throw(); - } - - [Fact] - public void can_parse_timespan_with_arguments() - { - var faker = new Faker(); - - faker.Parse("{{date.timespan(00:00:25)}}") - .Should().Be("00:00:15.0880571"); - } + private readonly ITestOutputHelper console; + + public ArgumentsTest(ITestOutputHelper console) + { + this.console = console; + } + + + [Fact] + public void can_parse_random_number_request_without_arguments() + { + var faker = new Faker(); + var result = faker.Parse("{{randomizer.number}}"); + int.Parse(result); + } + + [Fact] + public void can_parse_random_bool_request_without_arguments() + { + var faker = new Faker(); + var result = faker.Parse("{{randomizer.bool}}"); + bool.Parse(result); + } + + + [Fact] + public void can_parse_random_number_parameterized_request() + { + var faker = new Faker(); + var result = faker.Parse("{{randomizer.number (100)}}"); + int.Parse(result).Should().Be(60); + } + + [Fact] + public void can_parse_random_number_parameterized_request_overload() + { + var faker = new Faker(); + var result = faker.Parse("{{randomizer.number (50, 100)}}"); + int.Parse(result).Should().Be(80); + } + + [Fact] + public void cant_parse_random_number_parameterized_request_incorrect_overload() + { + var faker = new Faker(); + Assert.Throws(() => faker.Parse("{{randomizer.number (50, 100, 1000)}}")); + } + + [Fact] + public void cant_parse_random_number_parameterized_request_incorrect_type() + { + var faker = new Faker(); + Assert.Throws(() => faker.Parse("{{randomizer.number (a)}}")); + } + + [Fact] + public void cant_parse_random_string_request_with_not_enough_arguments() + { + var faker = new Faker(); + Assert.Throws(() => faker.Parse("{{randomizer.ReplaceNumbers}}")); + } + + [Fact] + public void can_parse_random_string_request_with_enough_arguments() + { + var faker = new Faker(); + faker.Parse("{{randomizer.string (5, 10)}}") + .Length.Should() + .BeGreaterOrEqualTo(5) + .And + .BeLessOrEqualTo(10); + } + + [Fact] + public void can_parse_random_string_request_with_full_arguments() + { + var faker = new Faker(); + faker.Parse("{{randomizer.string (5, 10, a, z)}}").Should().Be("cvqaqbrm"); + } + + [Fact] + public void can_parse_enum_argument() + { + var faker = new Faker(); + faker.Parse("{{name.firstname(Female)}} {{name.firstname(Male)}}").Should().Be("Lindsay Jonathan"); + } + + [Fact] + public void can_parse_string_argument() + { + var faker = new Faker(); + faker.Parse(@"{{randomizer.string2(9, wxyz)}}").Should().Be("ywzywywyx"); + } + + [Fact] + public void can_parse_bool_argument() + { + var faker = new Faker(); + faker.Parse(@"{{randomizer.hash(5, true)}}").Should().Be("91DA0"); + } + + [Fact] + public void can_parse_datetime_with_arguments() + { + var faker = new Faker(); + var dtString = faker.Parse("{{date.between(2015-10-04, 2017-11-03) }}"); + var dt = DateTimeOffset.Parse(dtString); + dt.Should() + .BeAfter(new DateTime(2015, 10, 04)) + .And + .BeBefore(new DateTime(2017, 11, 03)); + } + + [Fact] + public void unmached_brace_should_throw() + { + var faker = new Faker(); + //easy to miss the closing ) with }} handle bars. + Action a = () => faker.Parse("{{randomizer.number(100 }}"); + a.Should().Throw(); + } + + [Fact] + public void can_parse_timespan_with_arguments() + { + var faker = new Faker(); + + faker.Parse("{{date.timespan(00:00:25)}}") + .Should().Be("00:00:15.0880571"); } } diff --git a/Source/Bogus.Tests/LocaleTests/PtLocale.cs b/Source/Bogus.Tests/LocaleTests/PtLocale.cs index d2d1fd49..975c279d 100644 --- a/Source/Bogus.Tests/LocaleTests/PtLocale.cs +++ b/Source/Bogus.Tests/LocaleTests/PtLocale.cs @@ -2,48 +2,47 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.LocaleTests +namespace Bogus.Tests.LocaleTests; + +public class PtLocale : SeededTest { - public class PtLocale : SeededTest + [Fact] + public void address_test() + { + var a = new Address("pt_PT"); + a.CityPrefix().Should().Be("Vila Nova de"); + a.CitySuffix().Should().Be("do Douro"); + a.StreetSuffix().Should().Be("Viela"); + a.SecondaryAddress().Should().Be("Lote 06"); + a.State().Should().Be("Aveiro"); + } + + [Fact] + public void company_tests() { - [Fact] - public void address_test() - { - var a = new Address("pt_PT"); - a.CityPrefix().Should().Be("Vila Nova de"); - a.CitySuffix().Should().Be("do Douro"); - a.StreetSuffix().Should().Be("Viela"); - a.SecondaryAddress().Should().Be("Lote 06"); - a.State().Should().Be("Aveiro"); - } - - [Fact] - public void company_tests() - { - var c = new Company("pt_PT"); - - c.CompanySuffix().Should().Be("e Associados"); - c.CompanyName().Should().Be("Raposo e Associados"); - } - - [Fact] - public void name_tests() - { - var n = new Name("pt_PT"); - - n.Suffix().Should().Be("Neto"); - n.Prefix(Name.Gender.Female).Should().Be("Sra."); - } - - [Fact] - public void date_tests() - { - var d = new Date("pt_PT"); - - d.Month().Should().Be("Agosto"); - d.Month(abbreviation: true).Should().Be("Fev"); - d.Weekday().Should().Be("Sábado"); - d.Weekday(abbreviation:true).Should().Be("Sex"); - } + var c = new Company("pt_PT"); + + c.CompanySuffix().Should().Be("e Associados"); + c.CompanyName().Should().Be("Raposo e Associados"); + } + + [Fact] + public void name_tests() + { + var n = new Name("pt_PT"); + + n.Suffix().Should().Be("Neto"); + n.Prefix(Name.Gender.Female).Should().Be("Sra."); + } + + [Fact] + public void date_tests() + { + var d = new Date("pt_PT"); + + d.Month().Should().Be("Agosto"); + d.Month(abbreviation: true).Should().Be("Fev"); + d.Weekday().Should().Be("Sábado"); + d.Weekday(abbreviation:true).Should().Be("Sex"); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/LocaleTests/TrLocale.cs b/Source/Bogus.Tests/LocaleTests/TrLocale.cs index f032c2f4..593eca6b 100644 --- a/Source/Bogus.Tests/LocaleTests/TrLocale.cs +++ b/Source/Bogus.Tests/LocaleTests/TrLocale.cs @@ -3,22 +3,21 @@ using Xunit; using Xunit.Abstractions; -namespace Bogus.Tests.LocaleTests +namespace Bogus.Tests.LocaleTests; + +public class TrLocale : SeededTest { - public class TrLocale : SeededTest - { - private readonly ITestOutputHelper console; + private readonly ITestOutputHelper console; - public TrLocale(ITestOutputHelper console) - { - this.console = console; - } + public TrLocale(ITestOutputHelper console) + { + this.console = console; + } - [Fact] - public void ensure_tr_locale_lorem_is_used() - { - var l = new Lorem("tr"); - l.Sentence().Should().Be("Değerli voluptatem quia değirmeni sequi mi numquam."); - } + [Fact] + public void ensure_tr_locale_lorem_is_used() + { + var l = new Lorem("tr"); + l.Sentence().Should().Be("Değerli voluptatem quia değirmeni sequi mi numquam."); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/Models/Order.cs b/Source/Bogus.Tests/Models/Order.cs index f900c0a6..d43ad4f0 100644 --- a/Source/Bogus.Tests/Models/Order.cs +++ b/Source/Bogus.Tests/Models/Order.cs @@ -1,10 +1,8 @@ -namespace Bogus.Tests.Models -{ - public class Order - { - public int OrderId { get; set; } - public string Item { get; set; } - public int Quantity { get; set; } - } +namespace Bogus.Tests.Models; +public class Order +{ + public int OrderId { get; set; } + public string Item { get; set; } + public int Quantity { get; set; } } \ No newline at end of file diff --git a/Source/Bogus.Tests/PersonTest.cs b/Source/Bogus.Tests/PersonTest.cs index 4e97535d..82d0c6c0 100644 --- a/Source/Bogus.Tests/PersonTest.cs +++ b/Source/Bogus.Tests/PersonTest.cs @@ -12,238 +12,237 @@ using Xunit.Abstractions; using Z.ExtensionMethods.ObjectExtensions; -namespace Bogus.Tests +namespace Bogus.Tests; + +public class PersonTest : SeededTest { - public class PersonTest : SeededTest + private readonly ITestOutputHelper console; + + public PersonTest(ITestOutputHelper console) { - private readonly ITestOutputHelper console; - - public PersonTest(ITestOutputHelper console) - { - this.console = console; - } - - public class User - { - public string FirstName { get; set; } - public string Email { get; set; } - public string LastName { get; set; } - } - - [Fact] - public void new_person_on_every_generate() - { - var faker = new Faker() - .RuleFor(b => b.Email, f => f.Person.Email) - .RuleFor(b => b.FirstName, f => f.Person.FirstName) - .RuleFor(b => b.LastName, f => f.Person.LastName); - - var fakes = faker.Generate(3); - - fakes.Select(f => f.Email).Distinct().Count().Should().Be(3); - fakes.Select(f => f.FirstName).Distinct().Count().Should().Be(3); - fakes.Select(f => f.LastName).Distinct().Count().Should().Be(3); - } - - - [Fact] - public void check_ssn_on_person() - { - var p = new Person(); - p.Ssn().Should().Be("771-62-9016"); - } - - [Fact] - public void can_generate_valid_sin() - { - var obtained = Get(10, p => p.Sin()); - - console.Dump(obtained); - - var truth = new[] - { - "839 188 984", - "325 702 553", - "319 484 895", - "586 063 471", - "518 195 482", - "964 093 777", - "779 498 823", - "920 006 517", - "933 919 375", - "399 632 215" - }; - - obtained.Should().Equal(truth); - } - - [Fact] - public void can_generate_cpf_for_brazil() - { - var obtained = Get(10, p => p.Cpf()); - - console.Dump(obtained); - - var expect = new[] - { - "869.287.971-18", - "595.269.345-80", - "798.307.329-16", - "885.844.123-01", - "818.542.835-29", - "963.989.340-40", - "006.475.157-09", - "629.400.035-13", - "658.676.631-16", - "792.478.139-05" - }; - - obtained.Should().Equal(expect); - } - - [Fact] - public void can_generate_cpf_for_brazil_without_formatting() - { - var obtained = Get(10, p => p.Cpf(includeFormatSymbols: false)); - - console.Dump(obtained); - - var expect = new[] - { - "86928797118", - "59526934580", - "79830732916", - "88584412301", - "81854283529", - "96398934040", - "00647515709", - "62940003513", - "65867663116", - "79247813905" - }; - - obtained.Should().Equal(expect); - } - - [Fact] - public void can_generate_numeric_cpf_for_brazil() - { - var obtained = Get(10, p => p.Cpf(includeFormatSymbols: false).ToULong()); - - console.Dump(obtained); - - var expect = new ulong[] + this.console = console; + } + + public class User + { + public string FirstName { get; set; } + public string Email { get; set; } + public string LastName { get; set; } + } + + [Fact] + public void new_person_on_every_generate() + { + var faker = new Faker() + .RuleFor(b => b.Email, f => f.Person.Email) + .RuleFor(b => b.FirstName, f => f.Person.FirstName) + .RuleFor(b => b.LastName, f => f.Person.LastName); + + var fakes = faker.Generate(3); + + fakes.Select(f => f.Email).Distinct().Count().Should().Be(3); + fakes.Select(f => f.FirstName).Distinct().Count().Should().Be(3); + fakes.Select(f => f.LastName).Distinct().Count().Should().Be(3); + } + + + [Fact] + public void check_ssn_on_person() + { + var p = new Person(); + p.Ssn().Should().Be("771-62-9016"); + } + + [Fact] + public void can_generate_valid_sin() + { + var obtained = Get(10, p => p.Sin()); + + console.Dump(obtained); + + var truth = new[] + { + "839 188 984", + "325 702 553", + "319 484 895", + "586 063 471", + "518 195 482", + "964 093 777", + "779 498 823", + "920 006 517", + "933 919 375", + "399 632 215" + }; + + obtained.Should().Equal(truth); + } + + [Fact] + public void can_generate_cpf_for_brazil() + { + var obtained = Get(10, p => p.Cpf()); + + console.Dump(obtained); + + var expect = new[] + { + "869.287.971-18", + "595.269.345-80", + "798.307.329-16", + "885.844.123-01", + "818.542.835-29", + "963.989.340-40", + "006.475.157-09", + "629.400.035-13", + "658.676.631-16", + "792.478.139-05" + }; + + obtained.Should().Equal(expect); + } + + [Fact] + public void can_generate_cpf_for_brazil_without_formatting() + { + var obtained = Get(10, p => p.Cpf(includeFormatSymbols: false)); + + console.Dump(obtained); + + var expect = new[] + { + "86928797118", + "59526934580", + "79830732916", + "88584412301", + "81854283529", + "96398934040", + "00647515709", + "62940003513", + "65867663116", + "79247813905" + }; + + obtained.Should().Equal(expect); + } + + [Fact] + public void can_generate_numeric_cpf_for_brazil() + { + var obtained = Get(10, p => p.Cpf(includeFormatSymbols: false).ToULong()); + + console.Dump(obtained); + + var expect = new ulong[] + { + 86928797118, + 59526934580, + 79830732916, + 88584412301, + 81854283529, + 96398934040, + 00647515709, + 62940003513, + 65867663116, + 79247813905 + }; + + obtained.Should().Equal(expect); + } + + [Fact] + public void can_generate_cpr_number_for_denmark() + { + var p = new Person(); + var obtained = p.Cpr(); + + obtained.Dump(); + + var a = obtained.Split('-')[0]; + var b = obtained.Split('-')[1]; + + a.Length.Should().Be(6); + b.Length.Should().Be(4); + } + + [Fact] + public void can_generate_henkilötunnus_for_finland() + { + var p = new Person(); + var obtained = p.Henkilötunnus(); + + var a = obtained.Split('-')[0]; + var b = obtained.Split('-')[1]; + + a.Length.Should().Be(6); + b.Length.Should().Be(4); + } + + [Fact] + public void check_emails() + { + var emails = Get(10, p => p.Email); + + console.Dump(emails); + + emails.Should().ContainInOrder( + "Doris69@yahoo.com", + "Natasha_Turcotte19@hotmail.com", + "Melba47@gmail.com", + "Ismael.Murray3@gmail.com", + "Brendan.Beer51@yahoo.com", + "Kathleen_Nader@yahoo.com", + "Genevieve_Marvin@yahoo.com", + "Regina_Kirlin44@yahoo.com", + "Gerardo_Leannon@hotmail.com", + "Theodore_Gaylord24@hotmail.com" + ); + console.WriteLine(emails.DumpString()); + } + + [Fact] + public void person_has_full_name() + { + var p = new Person(); + p.FullName.Should().Be($"{p.FirstName} {p.LastName}"); + } + + [Fact] + public void can_use_local_seed_for_person() + { + Date.SystemClock = () => new DateTime(2019, 3, 21, 1, 1, 1); + + var p1 = new Person(seed: 1337); + var p2 = new Person(seed: 1337); + var q = new Person(seed: 7331); + + p1.FullName.Should().Be("Samuel Haley"); + p2.FullName.Should().Be(p1.FullName); + q.FullName.Should().Be("Lynette Beatty"); + q.FullName.Should().NotBe(p1.FullName); + + p1.FirstName.Should().Be(p2.FirstName); + p1.LastName.Should().Be(p2.LastName); + p1.Avatar.Should().Be(p2.Avatar); + p1.DateOfBirth.Should().Be(p2.DateOfBirth); + p1.Email.Should().Be(p2.Email); + p1.Phone.Should().Be(p2.Phone); + p1.UserName.Should().Be(p2.UserName); + p1.Gender.Should().Be(p2.Gender); + p1.Website.Should().Be(p2.Website); + + p1.Should().BeEquivalentTo(p2); + + Date.SystemClock = () => DateTime.Now; + } + + + IEnumerable Get(int times, Func a) + { + return Enumerable.Range(0, times) + .Select(i => { - 86928797118, - 59526934580, - 79830732916, - 88584412301, - 81854283529, - 96398934040, - 00647515709, - 62940003513, - 65867663116, - 79247813905 - }; - - obtained.Should().Equal(expect); - } - - [Fact] - public void can_generate_cpr_number_for_denmark() - { - var p = new Person(); - var obtained = p.Cpr(); - - obtained.Dump(); - - var a = obtained.Split('-')[0]; - var b = obtained.Split('-')[1]; - - a.Length.Should().Be(6); - b.Length.Should().Be(4); - } - - [Fact] - public void can_generate_henkilötunnus_for_finland() - { - var p = new Person(); - var obtained = p.Henkilötunnus(); - - var a = obtained.Split('-')[0]; - var b = obtained.Split('-')[1]; - - a.Length.Should().Be(6); - b.Length.Should().Be(4); - } - - [Fact] - public void check_emails() - { - var emails = Get(10, p => p.Email); - - console.Dump(emails); - - emails.Should().ContainInOrder( - "Doris69@yahoo.com", - "Natasha_Turcotte19@hotmail.com", - "Melba47@gmail.com", - "Ismael.Murray3@gmail.com", - "Brendan.Beer51@yahoo.com", - "Kathleen_Nader@yahoo.com", - "Genevieve_Marvin@yahoo.com", - "Regina_Kirlin44@yahoo.com", - "Gerardo_Leannon@hotmail.com", - "Theodore_Gaylord24@hotmail.com" - ); - console.WriteLine(emails.DumpString()); - } - - [Fact] - public void person_has_full_name() - { - var p = new Person(); - p.FullName.Should().Be($"{p.FirstName} {p.LastName}"); - } - - [Fact] - public void can_use_local_seed_for_person() - { - Date.SystemClock = () => new DateTime(2019, 3, 21, 1, 1, 1); - - var p1 = new Person(seed: 1337); - var p2 = new Person(seed: 1337); - var q = new Person(seed: 7331); - - p1.FullName.Should().Be("Samuel Haley"); - p2.FullName.Should().Be(p1.FullName); - q.FullName.Should().Be("Lynette Beatty"); - q.FullName.Should().NotBe(p1.FullName); - - p1.FirstName.Should().Be(p2.FirstName); - p1.LastName.Should().Be(p2.LastName); - p1.Avatar.Should().Be(p2.Avatar); - p1.DateOfBirth.Should().Be(p2.DateOfBirth); - p1.Email.Should().Be(p2.Email); - p1.Phone.Should().Be(p2.Phone); - p1.UserName.Should().Be(p2.UserName); - p1.Gender.Should().Be(p2.Gender); - p1.Website.Should().Be(p2.Website); - - p1.Should().BeEquivalentTo(p2); - - Date.SystemClock = () => DateTime.Now; - } - - - IEnumerable Get(int times, Func a) - { - return Enumerable.Range(0, times) - .Select(i => - { - var p = new Person(); - return a(p); - }).ToArray(); - } + var p = new Person(); + return a(p); + }).ToArray(); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/README_Generator.cs b/Source/Bogus.Tests/README_Generator.cs index 597d817b..b844c532 100644 --- a/Source/Bogus.Tests/README_Generator.cs +++ b/Source/Bogus.Tests/README_Generator.cs @@ -15,347 +15,346 @@ using Xunit.Abstractions; using Z.ExtensionMethods; -namespace Bogus.Tests +namespace Bogus.Tests; + +public class README_Generator { - public class README_Generator + private readonly ITestOutputHelper output; + + public README_Generator(ITestOutputHelper output) { - private readonly ITestOutputHelper output; + this.output = output; + } - public README_Generator(ITestOutputHelper output) - { - this.output = output; - } + public class Record + { + public string Dataset; + public string Method; + public string Summary; + } - public class Record - { - public string Dataset; - public string Method; - public string Summary; - } + [Fact] + public void get_available_methods() + { + var (_, buildDir) = GetWorkingFolders(); + var bogusXml = Path.Combine(buildDir, "Bogus.XML"); + var xml = XDocument.Load(bogusXml); + + var nav = xml.CreateNavigator(); + var sel = nav.Select("/doc/members/member"); - [Fact] - public void get_available_methods() + var list = new List(); + + foreach (XPathNavigator node in sel) { - var (_, buildDir) = GetWorkingFolders(); - var bogusXml = Path.Combine(buildDir, "Bogus.XML"); - var xml = XDocument.Load(bogusXml); + if( !node.HasAttributes ) continue; - var nav = xml.CreateNavigator(); - var sel = nav.Select("/doc/members/member"); + var member = node.GetAttribute("name", ""); + var summaryNode = node.SelectSingleNode("summary"); + if (summaryNode == null) continue; - var list = new List(); + var summary = summaryNode.ExtractContent() + .Replace("`System.", "`"); - foreach (XPathNavigator node in sel) + var declare = member; + var argPos = declare.IndexOf('('); + if (argPos > 0) { - if( !node.HasAttributes ) continue; + declare = declare.Substring(0, argPos); + } - var member = node.GetAttribute("name", ""); - var summaryNode = node.SelectSingleNode("summary"); - if (summaryNode == null) continue; + if( !declare.StartsWith("M:Bogus.DataSets.") ) continue; - var summary = summaryNode.ExtractContent() - .Replace("`System.", "`"); + var method = declare.TrimStart('M', ':'); + method = method.Replace("Bogus.DataSets.", ""); - var declare = member; - var argPos = declare.IndexOf('('); - if (argPos > 0) - { - declare = declare.Substring(0, argPos); - } + var methodSplit = method.Split('.'); - if( !declare.StartsWith("M:Bogus.DataSets.") ) continue; + var dataset = methodSplit[0]; + var call = methodSplit[1]; - var method = declare.TrimStart('M', ':'); - method = method.Replace("Bogus.DataSets.", ""); + if (call == "#ctor") continue; - var methodSplit = method.Split('.'); - - var dataset = methodSplit[0]; - var call = methodSplit[1]; + var r = new Record + { + Dataset = dataset, + Method = call, + Summary = summary + }; + list.Add(r); + } - if (call == "#ctor") continue; + var all = list + .GroupBy(k => k.Dataset) + .OrderBy(k => k.Key); - var r = new Record - { - Dataset = dataset, - Method = call, - Summary = summary - }; - list.Add(r); - } + //get all publicly accessible types. + var datasets = typeof(DataSet).Assembly.ExportedTypes + .Where(t => typeof(DataSet).IsAssignableFrom(t) && t != typeof(DataSet)) + .SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) + .Where( m => m.GetCustomAttribute() == null) + .Select(mi => new {dataset = mi.DeclaringType.Name, method = mi.Name}) + .GroupBy(g => g.dataset, u => u.method) + .ToDictionary(g => g.Key); - var all = list - .GroupBy(k => k.Dataset) - .OrderBy(k => k.Key); + foreach( var g in all ) + { + if( !datasets.ContainsKey(g.Key) ) return; //check if it's accessible + var methods = datasets[g.Key]; - //get all publicly accessible types. - var datasets = typeof(DataSet).Assembly.ExportedTypes - .Where(t => typeof(DataSet).IsAssignableFrom(t) && t != typeof(DataSet)) - .SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) - .Where( m => m.GetCustomAttribute() == null) - .Select(mi => new {dataset = mi.DeclaringType.Name, method = mi.Name}) - .GroupBy(g => g.dataset, u => u.method) - .ToDictionary(g => g.Key); + var distinctMethods = MoreEnumerable.DistinctBy(g, u => u.Method); - foreach( var g in all ) + output.WriteLine("* **`" + g.Key + "`**"); + foreach( var m in distinctMethods ) { - if( !datasets.ContainsKey(g.Key) ) return; //check if it's accessible - var methods = datasets[g.Key]; - - var distinctMethods = MoreEnumerable.DistinctBy(g, u => u.Method); - - output.WriteLine("* **`" + g.Key + "`**"); - foreach( var m in distinctMethods ) - { - if( !methods.Any(s => s.Contains(m.Method)) ) continue; //check if it's accessible - output.WriteLine("\t* `" + m.Method + "` - " + m.Summary); - } + if( !methods.Any(s => s.Contains(m.Method)) ) continue; //check if it's accessible + output.WriteLine("\t* `" + m.Method + "` - " + m.Summary); } } + } - [Fact] - public void get_randomizer_methods() - { - var (_, buildDir) = GetWorkingFolders(); - var bogusXml = Path.Combine(buildDir, "Bogus.XML"); - var xml = XDocument.Load(bogusXml); + [Fact] + public void get_randomizer_methods() + { + var (_, buildDir) = GetWorkingFolders(); + var bogusXml = Path.Combine(buildDir, "Bogus.XML"); + var xml = XDocument.Load(bogusXml); - var nav = xml.CreateNavigator(); - var sel = nav.Select("/doc/members/member"); + var nav = xml.CreateNavigator(); + var sel = nav.Select("/doc/members/member"); - var list = new List(); + var list = new List(); - foreach (XPathNavigator node in sel) - { - if (!node.HasAttributes) continue; + foreach (XPathNavigator node in sel) + { + if (!node.HasAttributes) continue; - var member = node.GetAttribute("name", ""); - var summaryNode = node.SelectSingleNode("summary"); - if (summaryNode == null) continue; + var member = node.GetAttribute("name", ""); + var summaryNode = node.SelectSingleNode("summary"); + if (summaryNode == null) continue; - var summary = summaryNode.ExtractContent() - .Replace("`System.", "`"); + var summary = summaryNode.ExtractContent() + .Replace("`System.", "`"); - var declare = member; - var argPos = declare.IndexOf('('); - if (argPos > 0) - { - declare = declare.Substring(0, argPos); - } + var declare = member; + var argPos = declare.IndexOf('('); + if (argPos > 0) + { + declare = declare.Substring(0, argPos); + } - if (!declare.StartsWith("M:Bogus.Randomizer.")) continue; + if (!declare.StartsWith("M:Bogus.Randomizer.")) continue; - if( summary.Contains("\r") ) - summary = summary.GetBefore("\r"); + if( summary.Contains("\r") ) + summary = summary.GetBefore("\r"); - var method = declare.TrimStart('M', ':'); - method = method.Replace("Bogus.", ""); + var method = declare.TrimStart('M', ':'); + method = method.Replace("Bogus.", ""); - var methodSplit = method.Split('.'); + var methodSplit = method.Split('.'); - var dataset = methodSplit[0]; - var call = methodSplit[1]; + var dataset = methodSplit[0]; + var call = methodSplit[1]; - if (call == "#ctor") continue; + if (call == "#ctor") continue; - call = call.Replace("``1", ""); + call = call.Replace("``1", ""); - var r = new Record - { - Dataset = dataset, - Method = call, - Summary = summary - }; - list.Add(r); - } + var r = new Record + { + Dataset = dataset, + Method = call, + Summary = summary + }; + list.Add(r); + } - var all = list - .GroupBy(k => k.Dataset) - .OrderBy(k => k.Key); + var all = list + .GroupBy(k => k.Dataset) + .OrderBy(k => k.Key); - //get all publicly accessible types. - var publicMethods = typeof(Randomizer) - .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) - .Select(mi => new {dataset = mi.DeclaringType.Name, method = mi.Name}); - //.GroupBy(g => g.dataset, u => u.method) - //.ToDictionary(g => g.Key); + //get all publicly accessible types. + var publicMethods = typeof(Randomizer) + .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .Select(mi => new {dataset = mi.DeclaringType.Name, method = mi.Name}); + //.GroupBy(g => g.dataset, u => u.method) + //.ToDictionary(g => g.Key); - foreach (var g in all) + foreach (var g in all) + { + //if (!datasets.ContainsKey(g.Key)) return; //check if it's accessible + var sortedMethods = g + .OrderBy(x => x.Method) + .ThenBy(x => x.Summary.Length); + var distinctMethods = MoreEnumerable.DistinctBy(sortedMethods, u => u.Method); + //we need to do this ordering so we select the most + //succinct description for any method overloads. + + //then just preserve the ordering as source code in source code + distinctMethods = g.Intersect(distinctMethods); + + output.WriteLine("* **`Random`/`" + g.Key + "`**"); + foreach (var m in distinctMethods) { - //if (!datasets.ContainsKey(g.Key)) return; //check if it's accessible - var sortedMethods = g - .OrderBy(x => x.Method) - .ThenBy(x => x.Summary.Length); - var distinctMethods = MoreEnumerable.DistinctBy(sortedMethods, u => u.Method); - //we need to do this ordering so we select the most - //succinct description for any method overloads. - - //then just preserve the ordering as source code in source code - distinctMethods = g.Intersect(distinctMethods); - - output.WriteLine("* **`Random`/`" + g.Key + "`**"); - foreach (var m in distinctMethods) - { - if (!publicMethods.Any(s => m.Method.Contains(s.method))) continue; //check if it's accessible - output.WriteLine("\t* `" + m.Method + "` - " + m.Summary); - } + if (!publicMethods.Any(s => m.Method.Contains(s.method))) continue; //check if it's accessible + output.WriteLine("\t* `" + m.Method + "` - " + m.Summary); } } + } - [Fact] - public void get_all_locales() - { - var data = Database.Data.Value; - - var locales = new List(); - - int count = 0; + [Fact] + public void get_all_locales() + { + var data = Database.Data.Value; - //load all locales - Database.GetAllLocales().Select(Database.GetLocale).ToArray(); + var locales = new List(); - var lcs = Database.Data.Value.OrderBy(kv => kv.Key).Select(kv => - { - count++; - var code = kv.Key; - var title = kv.Value["title"].StringValue; + int count = 0; - return new {code, title}; - }).ToArray(); + //load all locales + Database.GetAllLocales().Select(Database.GetLocale).ToArray(); - var col1 = lcs.Take(lcs.Length / 2 + lcs.Length % 2).ToArray(); - var col2 = lcs.Skip(lcs.Length / 2 + lcs.Length % 2).ToArray(); - - for( int i = 0; i < col1.Length; i++ ) + var lcs = Database.Data.Value.OrderBy(kv => kv.Key).Select(kv => { - var c1 = col1[i]; - var c2 = i == col2.Length ? null : col2[i]; + count++; + var code = kv.Key; + var title = kv.Value["title"].StringValue; - var c2code = c2 is null ? string.Empty : $"`{c2.code,-14}`"; - var c2title = c2 is null ? string.Empty : $"{c2.title,-26}"; + return new {code, title}; + }).ToArray(); - var str = $"|`{c1.code,-14}`|{c1.title,-26}||{c2code}|{c2title}|"; - locales.Add(str); - } + var col1 = lcs.Take(lcs.Length / 2 + lcs.Length % 2).ToArray(); + var col2 = lcs.Skip(lcs.Length / 2 + lcs.Length % 2).ToArray(); + for( int i = 0; i < col1.Length; i++ ) + { + var c1 = col1[i]; + var c2 = i == col2.Length ? null : col2[i]; - //make sure # of embedded locales matches the number of imported on disk. - //var workingDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); - var (projectDir, _) = GetWorkingFolders(); - var dataDir = projectDir.PathCombine(@"..\Bogus\data"); - count.Should().Be(Directory.GetFiles(dataDir, "*.locale.json").Length); + var c2code = c2 is null ? string.Empty : $"`{c2.code,-14}`"; + var c2title = c2 is null ? string.Empty : $"{c2.title,-26}"; - output.WriteLine(string.Join("\n", locales)); + var str = $"|`{c1.code,-14}`|{c1.title,-26}||{c2code}|{c2title}|"; + locales.Add(str); } - [Fact] - public void get_extension_namespaces() - { - var (_, buildDir) = GetWorkingFolders(); - var bogusXml = Path.Combine(buildDir, "Bogus.XML"); - var x = XElement.Load(bogusXml); - var json = JsonConvert.DeserializeObject(JsonConvert.SerializeXNode(x)); - var all = json.SelectTokens("doc.members.member").SelectMany(jt => jt) - .Select(m => - { - var member = m["@name"]; - var summary = m["summary"]; - if( member == null || summary == null ) return null; + //make sure # of embedded locales matches the number of imported on disk. + //var workingDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + var (projectDir, _) = GetWorkingFolders(); + var dataDir = projectDir.PathCombine(@"..\Bogus\data"); + count.Should().Be(Directory.GetFiles(dataDir, "*.locale.json").Length); - var declare = member.ToString(); - if( !declare.StartsWith("M:Bogus.Extensions.") ) return null; - - var method = declare.TrimStart('M', ':'); - if( method.Contains("#ctor") ) return null; + output.WriteLine(string.Join("\n", locales)); + } - //Bogus.Extensions.Canada.ExtensionsForCanada.Sin(Bogus.Person) - var ns = method.GetBetween("Bogus.Extensions.", ".ExtensionsFor"); - if( ns.IsNullOrEmpty() ) - { - return null; - } - ns = $"Bogus.Extensions.{ns}"; - var em = method.GetAfter("ExtensionsFor").GetAfter("."); + [Fact] + public void get_extension_namespaces() + { + var (_, buildDir) = GetWorkingFolders(); + var bogusXml = Path.Combine(buildDir, "Bogus.XML"); + var x = XElement.Load(bogusXml); + var json = JsonConvert.DeserializeObject(JsonConvert.SerializeXNode(x)); - return new {ns = ns, em = em, summary = summary.ToString().Trim()}; - }) - .Where(a => a != null) - .GroupBy(k => k.ns) - .OrderBy(k => k.Key); + var all = json.SelectTokens("doc.members.member").SelectMany(jt => jt) + .Select(m => + { + var member = m["@name"]; + var summary = m["summary"]; + if( member == null || summary == null ) return null; + var declare = member.ToString(); + if( !declare.StartsWith("M:Bogus.Extensions.") ) return null; - foreach( var g in all ) - { - output.WriteLine("* **`using " + g.Key + ";`**"); - foreach( var i in g ) - { - var method = i.em.GetBefore("("); - var objectExtends = i.em.GetBetween("(", ")"); - if( objectExtends.Contains(",") ) - objectExtends = objectExtends.GetBefore(","); - output.WriteLine($"\t* `{objectExtends}.{method}()` - {i.summary}"); - } - } - } + var method = declare.TrimStart('M', ':'); + if( method.Contains("#ctor") ) return null; + //Bogus.Extensions.Canada.ExtensionsForCanada.Sin(Bogus.Person) + var ns = method.GetBetween("Bogus.Extensions.", ".ExtensionsFor"); + if( ns.IsNullOrEmpty() ) + { + return null; + } + ns = $"Bogus.Extensions.{ns}"; + var em = method.GetAfter("ExtensionsFor").GetAfter("."); - //ReSharper, .NET Full Framework, and .NET Core all - //screw up the working folder path; this brings some - //sanity back. Very hack, but works. - private (string projectDir, string buildDir) GetWorkingFolders() - { - string FindRoot(string path) - { - if( path.ToUpperInvariant().EndsWith("BOGUS.TESTS") ) - return path; + return new {ns = ns, em = em, summary = summary.ToString().Trim()}; + }) + .Where(a => a != null) + .GroupBy(k => k.ns) + .OrderBy(k => k.Key); - return FindRoot(Path.GetFullPath(path.PathCombine(".."))); - } - var asmLoc = typeof(README_Generator).GetTypeInfo().Assembly.Location; - var asmDir = Path.GetDirectoryName(asmLoc); - var iniFile = Path.Combine(asmDir, "__AssemblyInfo__.ini"); - if( File.Exists(iniFile) ) + foreach( var g in all ) + { + output.WriteLine("* **`using " + g.Key + ";`**"); + foreach( var i in g ) { - var content = File.ReadAllText(iniFile, Encoding.Unicode); - var file = content.GetAfter("file:///").GetBefore("\0"); - return (FindRoot(file), Path.GetDirectoryName(file)); + var method = i.em.GetBefore("("); + var objectExtends = i.em.GetBetween("(", ")"); + if( objectExtends.Contains(",") ) + objectExtends = objectExtends.GetBefore(","); + output.WriteLine($"\t* `{objectExtends}.{method}()` - {i.summary}"); } - - return (FindRoot(asmLoc), Path.GetDirectoryName(asmLoc)); } } - public static class XmlExtensions + //ReSharper, .NET Full Framework, and .NET Core all + //screw up the working folder path; this brings some + //sanity back. Very hack, but works. + private (string projectDir, string buildDir) GetWorkingFolders() { - private static Regex ParamPattern = new Regex(@"<(see|paramref) (name|cref)=""([TPF]{1}:)?(?.+?)"" />"); - private static Regex ConstPattern = new Regex(@"(?.+?)"); - /// - /// Extracts the display content of the specified , replacing - /// paramref and c tags with a human-readable equivalent. - /// - /// The XML node from which to extract content. - /// The extracted content. - public static string ExtractContent(this XPathNavigator node) - { - if (node == null) return null; - return ConstPattern.Replace( - ParamPattern.Replace(node.InnerXml, GetParamRefName), - GetConstRefName).Trim(); - } - private static string GetConstRefName(Match match) + string FindRoot(string path) { - if (match.Groups.Count != 2) return null; - return match.Groups["display"].Value; + if( path.ToUpperInvariant().EndsWith("BOGUS.TESTS") ) + return path; + + return FindRoot(Path.GetFullPath(path.PathCombine(".."))); } - private static string GetParamRefName(Match match) + + var asmLoc = typeof(README_Generator).GetTypeInfo().Assembly.Location; + var asmDir = Path.GetDirectoryName(asmLoc); + var iniFile = Path.Combine(asmDir, "__AssemblyInfo__.ini"); + if( File.Exists(iniFile) ) { - if (match.Groups.Count != 5) return null; - return "`" + match.Groups["display"].Value + "`"; + var content = File.ReadAllText(iniFile, Encoding.Unicode); + var file = content.GetAfter("file:///").GetBefore("\0"); + return (FindRoot(file), Path.GetDirectoryName(file)); } + + return (FindRoot(asmLoc), Path.GetDirectoryName(asmLoc)); + } +} + + +public static class XmlExtensions +{ + private static Regex ParamPattern = new Regex(@"<(see|paramref) (name|cref)=""([TPF]{1}:)?(?.+?)"" />"); + private static Regex ConstPattern = new Regex(@"(?.+?)"); + /// + /// Extracts the display content of the specified , replacing + /// paramref and c tags with a human-readable equivalent. + /// + /// The XML node from which to extract content. + /// The extracted content. + public static string ExtractContent(this XPathNavigator node) + { + if (node == null) return null; + return ConstPattern.Replace( + ParamPattern.Replace(node.InnerXml, GetParamRefName), + GetConstRefName).Trim(); + } + private static string GetConstRefName(Match match) + { + if (match.Groups.Count != 2) return null; + return match.Groups["display"].Value; + } + private static string GetParamRefName(Match match) + { + if (match.Groups.Count != 5) return null; + return "`" + match.Groups["display"].Value + "`"; } } \ No newline at end of file diff --git a/Source/Bogus.Tests/RandomizerTest.cs b/Source/Bogus.Tests/RandomizerTest.cs index 6d8e82e4..b5e945b9 100644 --- a/Source/Bogus.Tests/RandomizerTest.cs +++ b/Source/Bogus.Tests/RandomizerTest.cs @@ -6,560 +6,559 @@ using Xunit; using Xunit.Abstractions; -namespace Bogus.Tests +namespace Bogus.Tests; + +public class RandomizerTest : SeededTest { - public class RandomizerTest : SeededTest + private readonly ITestOutputHelper console; + private Randomizer r; + + public RandomizerTest(ITestOutputHelper console) { - private readonly ITestOutputHelper console; - private Randomizer r; + this.console = console; + r = new Randomizer(); + } - public RandomizerTest(ITestOutputHelper console) - { - this.console = console; - r = new Randomizer(); - } + public enum Foo + { + ExcludeMe, + A, + B, + C, + D + } - public enum Foo - { - ExcludeMe, - A, - B, - C, - D - } + [Fact] + public void pick_an_enum() + { + var f = r.Enum(); + f.Should().Be(Foo.C); + } - [Fact] - public void pick_an_enum() - { - var f = r.Enum(); - f.Should().Be(Foo.C); - } + [Fact] + public void exclude_an_enum() + { + //seeded value of 14 gets "ExcludeMe", ensure exclude works. + Randomizer.Seed = new Random(14); + var f = r.Enum(exclude: Foo.ExcludeMe); + f.ToString().Dump(); - [Fact] - public void exclude_an_enum() - { - //seeded value of 14 gets "ExcludeMe", ensure exclude works. - Randomizer.Seed = new Random(14); - var f = r.Enum(exclude: Foo.ExcludeMe); - f.ToString().Dump(); + f.Should().NotBe(Foo.ExcludeMe); + } - f.Should().NotBe(Foo.ExcludeMe); - } + [Fact] + public void exclude_all_throws_an_error() + { + Action act = () => r.Enum(Foo.ExcludeMe, Foo.A, Foo.B, Foo.C, Foo.D); - [Fact] - public void exclude_all_throws_an_error() - { - Action act = () => r.Enum(Foo.ExcludeMe, Foo.A, Foo.B, Foo.C, Foo.D); + act.Should().Throw(); + } - act.Should().Throw(); - } + [Fact] + public void can_replace_numbers_or_letters_using_asterisk() + { + r.Replace("***") + .Should().Be("CQ6"); + } - [Fact] - public void can_replace_numbers_or_letters_using_asterisk() - { - r.Replace("***") - .Should().Be("CQ6"); - } + [Fact] + public void can_get_random_word() + { + r.Word().Should().Be("Court"); + r.Word().Should().Be("bluetooth"); + r.Word().Should().Be("Movies & Clothing"); + } - [Fact] - public void can_get_random_word() - { - r.Word().Should().Be("Court"); - r.Word().Should().Be("bluetooth"); - r.Word().Should().Be("Movies & Clothing"); - } + [Fact] + public void can_get_some_random_words() + { + r.Words().Should().Be("Soft deposit"); + r.Words().Should().Be("Handcrafted Granite Gloves Directives"); + r.Words().Should().Be("Corner Handcrafted Frozen Chair transmitting"); + } - [Fact] - public void can_get_some_random_words() - { - r.Words().Should().Be("Soft deposit"); - r.Words().Should().Be("Handcrafted Granite Gloves Directives"); - r.Words().Should().Be("Corner Handcrafted Frozen Chair transmitting"); - } + [Fact] + public void can_shuffle_some_enumerable() + { + new string(r.Shuffle("123456789").ToArray()) + .Should().Be("628753491"); + } - [Fact] - public void can_shuffle_some_enumerable() - { - new string(r.Shuffle("123456789").ToArray()) - .Should().Be("628753491"); - } + [Fact] + public void can_get_random_locale() + { + r.RandomLocale().Should().Be("ja"); + } - [Fact] - public void can_get_random_locale() - { - r.RandomLocale().Should().Be("ja"); - } + [Fact] + public void can_include_int_maxvalue_number() + { + var max = r.Number(int.MaxValue, int.MaxValue); + max.Should().Be(int.MaxValue); + } - [Fact] - public void can_include_int_maxvalue_number() - { - var max = r.Number(int.MaxValue, int.MaxValue); - max.Should().Be(int.MaxValue); - } + [Fact] + public void can_handle_full_int_range() + { + r.Number(int.MinValue, int.MaxValue); + } - [Fact] - public void can_handle_full_int_range() - { - r.Number(int.MinValue, int.MaxValue); - } + [Fact] + public void detects_invalid_Even_range() + { + Action act1 = () => r.Even(min: 1, max: 0); + act1.Should().Throw() + .Where( ex => ex.Message.StartsWith("The min/max range is invalid. The minimum value '1' is greater than the maximum value '0'.")); - [Fact] - public void detects_invalid_Even_range() - { - Action act1 = () => r.Even(min: 1, max: 0); - act1.Should().Throw() - .Where( ex => ex.Message.StartsWith("The min/max range is invalid. The minimum value '1' is greater than the maximum value '0'.")); + Action act2 = () => r.Even(min: int.MaxValue, max: int.MinValue); + act2.Should().Throw() + .Where( ex => ex.Message.StartsWith("The min/max range is invalid. The minimum value '2147483647' is greater than the maximum value '-2147483648'.")); + } - Action act2 = () => r.Even(min: int.MaxValue, max: int.MinValue); - act2.Should().Throw() - .Where( ex => ex.Message.StartsWith("The min/max range is invalid. The minimum value '2147483647' is greater than the maximum value '-2147483648'.")); - } + [Fact] + public void detects_empty_Even_range() + { + Action act1 = () => r.Even(min: 1, max: 1); + act1.Should().Throw() + .Where(ex => ex.Message.StartsWith("The specified range does not contain any even numbers.")); - [Fact] - public void detects_empty_Even_range() - { - Action act1 = () => r.Even(min: 1, max: 1); - act1.Should().Throw() - .Where(ex => ex.Message.StartsWith("The specified range does not contain any even numbers.")); + Action act2 = () => r.Even(min: int.MaxValue, max: int.MaxValue); + act2.Should().Throw() + .Where(ex => ex.Message.StartsWith("The specified range does not contain any even numbers.")); - Action act2 = () => r.Even(min: int.MaxValue, max: int.MaxValue); - act2.Should().Throw() - .Where(ex => ex.Message.StartsWith("The specified range does not contain any even numbers.")); + Action act3 = () => r.Even(min: int.MinValue + 1, max: int.MinValue + 1); + act3.Should().Throw() + .Where(ex => ex.Message.StartsWith("The specified range does not contain any even numbers.")); + } - Action act3 = () => r.Even(min: int.MinValue + 1, max: int.MinValue + 1); - act3.Should().Throw() - .Where(ex => ex.Message.StartsWith("The specified range does not contain any even numbers.")); - } + [Fact] + public void can_handle_extreme_Even_range() + { + r.Even(min: int.MinValue, max: int.MinValue).Should().Be(int.MinValue); + r.Even(min: int.MaxValue & ~1, max: int.MaxValue & ~1).Should().Be(int.MaxValue & ~1); + } - [Fact] - public void can_handle_extreme_Even_range() - { - r.Even(min: int.MinValue, max: int.MinValue).Should().Be(int.MinValue); - r.Even(min: int.MaxValue & ~1, max: int.MaxValue & ~1).Should().Be(int.MaxValue & ~1); - } + [Fact] + public void detects_invalid_Odd_range() + { + Action act1 = () => r.Odd(min: 1, max: 0); + act1.Should().Throw() + .Where(ex => ex.Message.StartsWith("The min/max range is invalid. The minimum value '1' is greater than the maximum value '0'.")); - [Fact] - public void detects_invalid_Odd_range() - { - Action act1 = () => r.Odd(min: 1, max: 0); - act1.Should().Throw() - .Where(ex => ex.Message.StartsWith("The min/max range is invalid. The minimum value '1' is greater than the maximum value '0'.")); + Action act2 = () => r.Odd(min: int.MaxValue, max: int.MinValue); + act2.Should().Throw() + .Where(ex => ex.Message.StartsWith("The min/max range is invalid. The minimum value '2147483647' is greater than the maximum value '-2147483648'.")); + } - Action act2 = () => r.Odd(min: int.MaxValue, max: int.MinValue); - act2.Should().Throw() - .Where(ex => ex.Message.StartsWith("The min/max range is invalid. The minimum value '2147483647' is greater than the maximum value '-2147483648'.")); - } + [Fact] + public void detects_empty_Odd_range() + { + Action act1 = () => r.Odd(min: 0, max: 0); + act1.Should().Throw() + .Where(ex => ex.Message.StartsWith("The specified range does not contain any odd numbers.")); - [Fact] - public void detects_empty_Odd_range() - { - Action act1 = () => r.Odd(min: 0, max: 0); - act1.Should().Throw() - .Where(ex => ex.Message.StartsWith("The specified range does not contain any odd numbers.")); + Action act2 = () => r.Odd(min: int.MaxValue - 1, max: int.MaxValue - 1); + act2.Should().Throw() + .Where(ex => ex.Message.StartsWith("The specified range does not contain any odd numbers.")); - Action act2 = () => r.Odd(min: int.MaxValue - 1, max: int.MaxValue - 1); - act2.Should().Throw() - .Where(ex => ex.Message.StartsWith("The specified range does not contain any odd numbers.")); + Action act3 = () => r.Odd(min: int.MinValue, max: int.MinValue); + act3.Should().Throw() + .Where(ex => ex.Message.StartsWith("The specified range does not contain any odd numbers.")); + } - Action act3 = () => r.Odd(min: int.MinValue, max: int.MinValue); - act3.Should().Throw() - .Where(ex => ex.Message.StartsWith("The specified range does not contain any odd numbers.")); - } + [Fact] + public void can_handle_extreme_Odd_range() + { + r.Odd(min: int.MinValue | 1, max: int.MinValue | 1).Should().Be(int.MinValue | 1); + r.Odd(min: int.MaxValue, max: int.MaxValue).Should().Be(int.MaxValue); + } - [Fact] - public void can_handle_extreme_Odd_range() - { - r.Odd(min: int.MinValue | 1, max: int.MinValue | 1).Should().Be(int.MinValue | 1); - r.Odd(min: int.MaxValue, max: int.MaxValue).Should().Be(int.MaxValue); - } + [Fact] + public void random_bool() + { + r.Bool().Should().BeFalse(); + } - [Fact] - public void random_bool() - { - r.Bool().Should().BeFalse(); - } + [Fact] + public void can_get_some_alpha_chars() + { + r.AlphaNumeric(20).Should().Be("l3tn1m1ohax6ql31pw1u"); + } - [Fact] - public void can_get_some_alpha_chars() - { - r.AlphaNumeric(20).Should().Be("l3tn1m1ohax6ql31pw1u"); - } + [Fact] + public void generate_double_with_min_and_max() + { + r.Double(2.5, 2.9).Should().BeInRange(2.74140891332244, 2.74140891332246); + } - [Fact] - public void generate_double_with_min_and_max() - { - r.Double(2.5, 2.9).Should().BeInRange(2.74140891332244, 2.74140891332246); - } + [Fact] + public void generate_decimal_with_min_and_max() + { + r.Decimal(2.2m, 5.2m).Should().Be(4.0105668499183690m); + } - [Fact] - public void generate_decimal_with_min_and_max() - { - r.Decimal(2.2m, 5.2m).Should().Be(4.0105668499183690m); - } + [Fact] + public void generate_float_with_min_and_max() + { + r.Float(2.7f, 3.9f).Should().BeInRange(3.424226f, 3.424228f); + } - [Fact] - public void generate_float_with_min_and_max() - { - r.Float(2.7f, 3.9f).Should().BeInRange(3.424226f, 3.424228f); - } + [Fact] + public void generate_byte() + { + r.Byte(1, 128).Should().Be(78); + } - [Fact] - public void generate_byte() - { - r.Byte(1, 128).Should().Be(78); - } + [Fact] + public void generate_some_bytes() + { + r.Bytes(20).Should() + .Equal(218, 35, 156, 76, 224, 196, 45, 215, 227, 196, 168, 150, 23, 242, 85, 178, 101, 200, 89, 189); + } - [Fact] - public void generate_some_bytes() - { - r.Bytes(20).Should() - .Equal(218, 35, 156, 76, 224, 196, 45, 215, 227, 196, 168, 150, 23, 242, 85, 178, 101, 200, 89, 189); - } + [Fact] + public void generate__sbyte() + { + r.SByte(max: 0).Should().Be(-51); + } - [Fact] - public void generate__sbyte() - { - r.SByte(max: 0).Should().Be(-51); - } + [Fact] + public void generate_uint32() + { + r.UInt(99, 200).Should().Be(160); + } - [Fact] - public void generate_uint32() - { - r.UInt(99, 200).Should().Be(160); - } + [Fact] + public void generate_unit32_many() + { + r.UInt().Should().Be(2592108469u); + r.UInt().Should().Be(471320134u); + r.UInt().Should().Be(3498684729u); + r.UInt().Should().Be(2775978649u); + } - [Fact] - public void generate_unit32_many() - { - r.UInt().Should().Be(2592108469u); - r.UInt().Should().Be(471320134u); - r.UInt().Should().Be(3498684729u); - r.UInt().Should().Be(2775978649u); - } + [Fact] + public void generate_int32() + { + r.Int(max: 0).Should().Be(-425714706); + } - [Fact] - public void generate_int32() - { - r.Int(max: 0).Should().Be(-425714706); - } + [Fact] + public void generate_int32_many() + { + r.Int().Should().Be(1077349347); + r.Int().Should().Be(1155054345); + r.Int().Should().Be(-1904480771); + r.Int().Should().Be(2101046113); + r.Int().Should().Be(1223601157); + r.Int().Should().Be(-594397672); + } - [Fact] - public void generate_int32_many() - { - r.Int().Should().Be(1077349347); - r.Int().Should().Be(1155054345); - r.Int().Should().Be(-1904480771); - r.Int().Should().Be(2101046113); - r.Int().Should().Be(1223601157); - r.Int().Should().Be(-594397672); - } + [Fact] + public void generate_uint64() + { + r.ULong(99, 9999).Should().Be(6074); + } - [Fact] - public void generate_uint64() - { - r.ULong(99, 9999).Should().Be(6074); - } + [Fact] + public void generate_uint64_many() + { + r.ULong().Should().Be(11133021102928879616UL); + r.ULong().Should().Be(2024304562418978048UL); + r.ULong().Should().Be(15026736492772024320UL); + r.ULong().Should().Be(11922737513106253824UL); + } - [Fact] - public void generate_uint64_many() - { - r.ULong().Should().Be(11133021102928879616UL); - r.ULong().Should().Be(2024304562418978048UL); - r.ULong().Should().Be(15026736492772024320UL); - r.ULong().Should().Be(11922737513106253824UL); - } + [Fact] + public void generate_int64() + { + r.Long(max: 0).Should().Be(-3656861485390335055L); + } - [Fact] - public void generate_int64() - { - r.Long(max: 0).Should().Be(-3656861485390335055L); - } + [Fact] + public void generate_int64_many() + { + r.Long().Should().Be(1909649066074105698L); + r.Long().Should().Be(-7199067474435792608L); + r.Long().Should().Be(5803364455917250112L); + r.Long().Should().Be(2699365476251477286L); + r.Long().Should().Be(-8566699986853958425L); + } - [Fact] - public void generate_int64_many() - { - r.Long().Should().Be(1909649066074105698L); - r.Long().Should().Be(-7199067474435792608L); - r.Long().Should().Be(5803364455917250112L); - r.Long().Should().Be(2699365476251477286L); - r.Long().Should().Be(-8566699986853958425L); - } + [Fact] + public void generate_int16() + { + r.Short(max: 0).Should().Be(-12992); + } - [Fact] - public void generate_int16() - { - r.Short(max: 0).Should().Be(-12992); - } + [Fact] + public void generate_int16_many() + { + r.Short().Should().Be(6784); + r.Short().Should().Be(-25576); + r.Short().Should().Be(20617); + r.Short().Should().Be(9589); + } - [Fact] - public void generate_int16_many() - { - r.Short().Should().Be(6784); - r.Short().Should().Be(-25576); - r.Short().Should().Be(20617); - r.Short().Should().Be(9589); - } + [Fact] + public void generate_uint16() + { + r.UShort().Should().Be(39552); + } - [Fact] - public void generate_uint16() - { - r.UShort().Should().Be(39552); - } + [Fact] + public void generate_char() + { + r.Char().Should().Be('\u9a80'); + } - [Fact] - public void generate_char() - { - r.Char().Should().Be('\u9a80'); - } + [Fact] + public void generate_some_chars() + { + r.Chars(count: 10).Should().Equal( + '\u9a80', + '\u1c17', + '\ud089', + '\ua576', + '\u091c', + '\u9fdb', + '\u0cfa', + '\ub0d6', + '\u7a91', + '\u4d58'); + } - [Fact] - public void generate_some_chars() - { - r.Chars(count: 10).Should().Equal( - '\u9a80', - '\u1c17', - '\ud089', - '\ua576', - '\u091c', - '\u9fdb', - '\u0cfa', - '\ub0d6', - '\u7a91', - '\u4d58'); - } + [Fact] + public void generate_string_range_check() + { + r.String() + .Length.Should() + .BeGreaterOrEqualTo(40) + .And + .BeLessOrEqualTo(80); + } - [Fact] - public void generate_string_range_check() - { - r.String() - .Length.Should() - .BeGreaterOrEqualTo(40) - .And - .BeLessOrEqualTo(80); - } + [Fact] + public void generate_string_byte_check() + { + var x = r.String(3); - [Fact] - public void generate_string_byte_check() - { - var x = r.String(3); - - x.Length.Should().Be(3); - - var rawBytes = new byte[] - { - 233, - 170, - 128, - 225, - 176, - 151, - 237, - 130, - 137 - }; - - Encoding.UTF8.GetBytes(x) - .Should().Equal(rawBytes); - } + x.Length.Should().Be(3); - [Fact] - public void generate_string_AZ() - { - r.String(minChar: 'A', maxChar: 'Z') - .Should().Be("CVQAQBRMHYESPCASXAVVIPPCRZKFPOFICRUEYZGQKYXUWMHOBLCFHCHMFOJRRMXT"); - } + var rawBytes = new byte[] + { + 233, + 170, + 128, + 225, + 176, + 151, + 237, + 130, + 137 + }; + + Encoding.UTF8.GetBytes(x) + .Should().Equal(rawBytes); + } - [Fact] - public void generate_string2_pool() - { - r.String2(5).Should().Be("pcvqa"); - } + [Fact] + public void generate_string_AZ() + { + r.String(minChar: 'A', maxChar: 'Z') + .Should().Be("CVQAQBRMHYESPCASXAVVIPPCRZKFPOFICRUEYZGQKYXUWMHOBLCFHCHMFOJRRMXT"); + } - [Fact] - public void generate_string2_pool_custom() - { - r.String2(5, "abc").Should().Be("bacba"); - } + [Fact] + public void generate_string2_pool() + { + r.String2(5).Should().Be("pcvqa"); + } - [Fact] - public void generate_string2_pool_min_max() - { - var x = r.String2(5, 10, "xyz"); + [Fact] + public void generate_string2_pool_custom() + { + r.String2(5, "abc").Should().Be("bacba"); + } - x.Length.Should() - .BeGreaterOrEqualTo(5) - .And - .BeLessOrEqualTo(10); + [Fact] + public void generate_string2_pool_min_max() + { + var x = r.String2(5, 10, "xyz"); - x.Should().Be("xzyxyxzy"); - } + x.Length.Should() + .BeGreaterOrEqualTo(5) + .And + .BeLessOrEqualTo(10); - [Fact] - public void generate_hash() - { - r.Hash().Should().Be("91da090b74f2b910be0dd5991af6398351ac2ef3"); - } + x.Should().Be("xzyxyxzy"); + } - [Fact] - public void generate_small_hash() - { - r.Hash(20).Should().Be("91da090b74f2b910be0d"); - } + [Fact] + public void generate_hash() + { + r.Hash().Should().Be("91da090b74f2b910be0dd5991af6398351ac2ef3"); + } - [Fact] - public void random_word_tests() - { - //r.Words(3).Should().Be(""); - //r.Words(5).Split(' ').Length.Should().Be(4); - r.WordsArray(5).Length.Should().Be(5); - r.WordsArray(1, 80).Length.Should().BeInRange(1, 80); //.Should().BeInRange(1, 80); - r.WordsArray(10, 20).Length.Should().BeInRange(10, 20); - } + [Fact] + public void generate_small_hash() + { + r.Hash(20).Should().Be("91da090b74f2b910be0d"); + } - [Fact] - public void can_pick_random_item_from_ICollection() - { - var x = new List {1, 2, 3} as ICollection; + [Fact] + public void random_word_tests() + { + //r.Words(3).Should().Be(""); + //r.Words(5).Split(' ').Length.Should().Be(4); + r.WordsArray(5).Length.Should().Be(5); + r.WordsArray(1, 80).Length.Should().BeInRange(1, 80); //.Should().BeInRange(1, 80); + r.WordsArray(10, 20).Length.Should().BeInRange(10, 20); + } - r.CollectionItem(x).Should().BeOneOf(1, 2, 3); - } + [Fact] + public void can_pick_random_item_from_ICollection() + { + var x = new List {1, 2, 3} as ICollection; - [Fact] - public void throw_an_exception_when_picking_nothing_from_collection() - { - var x = new List() as ICollection; - Action act = () => r.CollectionItem(x); - act.Should().Throw(); - } + r.CollectionItem(x).Should().BeOneOf(1, 2, 3); + } - [Fact] - public void can_pick_random_item_from_ilist() - { - var x = new List {1, 2, 3} as IList; + [Fact] + public void throw_an_exception_when_picking_nothing_from_collection() + { + var x = new List() as ICollection; + Action act = () => r.CollectionItem(x); + act.Should().Throw(); + } - r.ListItem(x).Should().BeOneOf(1, 2, 3); - } + [Fact] + public void can_pick_random_item_from_ilist() + { + var x = new List {1, 2, 3} as IList; - [Fact] - public void can_pick_random_item_from_list() - { - var x = new List {1, 2, 3}; + r.ListItem(x).Should().BeOneOf(1, 2, 3); + } - r.ListItem(x).Should().BeOneOf(1, 2, 3); - } + [Fact] + public void can_pick_random_item_from_list() + { + var x = new List {1, 2, 3}; - [Fact] - public void can_generate_hexdec_string() - { - r.Hexadecimal().Should().StartWith("0x").And.Be("0x9"); - r.Hexadecimal(20).Should().Be("0x1da090b74f2b910be0dd"); - r.Hexadecimal(prefix: "").Should().Be("5"); - } + r.ListItem(x).Should().BeOneOf(1, 2, 3); + } - [Fact] - public void can_get_random_subset_of_an_array() - { - var a = new[] {"a", "b", "c"}; - r.ArrayElements(a).Should().Equal("a"); + [Fact] + public void can_generate_hexdec_string() + { + r.Hexadecimal().Should().StartWith("0x").And.Be("0x9"); + r.Hexadecimal(20).Should().Be("0x1da090b74f2b910be0dd"); + r.Hexadecimal(prefix: "").Should().Be("5"); + } - r.ArrayElements(a, 2).Should().Equal("c", "a"); - } + [Fact] + public void can_get_random_subset_of_an_array() + { + var a = new[] {"a", "b", "c"}; + r.ArrayElements(a).Should().Equal("a"); - [Fact] - public void can_get_random_subset_of_a_list() - { - var a = new List {"a", "b", "c"}; - r.ListItems(a).Should().Equal("a"); + r.ArrayElements(a, 2).Should().Equal("c", "a"); + } - r.ListItems(a, 2).Should().Equal("c", "a"); - } + [Fact] + public void can_get_random_subset_of_a_list() + { + var a = new List {"a", "b", "c"}; + r.ListItems(a).Should().Equal("a"); - [Fact] - public void can_get_a_weighted_true_value() - { - var bools = Enumerable.Range(1, 100).Select(i => r.Bool(0.20f)); - var truths = bools.Count(b => b) / 100f; + r.ListItems(a, 2).Should().Equal("c", "a"); + } - truths.Should().BeLessThan(0.25f); // roughly - } + [Fact] + public void can_get_a_weighted_true_value() + { + var bools = Enumerable.Range(1, 100).Select(i => r.Bool(0.20f)); + var truths = bools.Count(b => b) / 100f; + truths.Should().BeLessThan(0.25f); // roughly + } - public static IEnumerable ExactLenUtf16(int maxTest) - { - return Enumerable.Range(1, maxTest) - .Select(i => new object[] {i, i}); - } - public static IEnumerable VarLenUtf16(int maxTest) - { - return Enumerable.Range(1, maxTest) - .Select(i => new object[] { i, i+20 }); - } + public static IEnumerable ExactLenUtf16(int maxTest) + { + return Enumerable.Range(1, maxTest) + .Select(i => new object[] {i, i}); + } - [Theory] - [MemberData(nameof(ExactLenUtf16), parameters: 100)] - [MemberData(nameof(VarLenUtf16), parameters: 100)] - public void can_generate_valid_utf16_string_with_surrogates(int min, int max) - { - var x = r.Utf16String(min, max); + public static IEnumerable VarLenUtf16(int maxTest) + { + return Enumerable.Range(1, maxTest) + .Select(i => new object[] { i, i+20 }); + } + + [Theory] + [MemberData(nameof(ExactLenUtf16), parameters: 100)] + [MemberData(nameof(VarLenUtf16), parameters: 100)] + public void can_generate_valid_utf16_string_with_surrogates(int min, int max) + { + var x = r.Utf16String(min, max); - x.Length.Should().BeGreaterOrEqualTo(min) - .And - .BeLessOrEqualTo(max); + x.Length.Should().BeGreaterOrEqualTo(min) + .And + .BeLessOrEqualTo(max); - for( int i = 0; i < x.Length; i++ ) + for( int i = 0; i < x.Length; i++ ) + { + var current = x[i]; + if( char.IsSurrogate(current) ) + { + char.IsLetterOrDigit(x, i).Should().BeTrue(); + i++; + } + else { - var current = x[i]; - if( char.IsSurrogate(current) ) - { - char.IsLetterOrDigit(x, i).Should().BeTrue(); - i++; - } - else - { - char.IsLetterOrDigit(current).Should().BeTrue(); - } + char.IsLetterOrDigit(current).Should().BeTrue(); } } + } - [Theory] - [MemberData(nameof(ExactLenUtf16), parameters: 100)] - [MemberData(nameof(VarLenUtf16), parameters: 100)] - public void can_generate_valid_utf16_without_surrogates(int min, int max) - { - var x = r.Utf16String(min, max, excludeSurrogates: true); + [Theory] + [MemberData(nameof(ExactLenUtf16), parameters: 100)] + [MemberData(nameof(VarLenUtf16), parameters: 100)] + public void can_generate_valid_utf16_without_surrogates(int min, int max) + { + var x = r.Utf16String(min, max, excludeSurrogates: true); - x.Length.Should().BeGreaterOrEqualTo(min) - .And - .BeLessOrEqualTo(max); + x.Length.Should().BeGreaterOrEqualTo(min) + .And + .BeLessOrEqualTo(max); - x.Any(char.IsSurrogate).Should().BeFalse(); - x.All(char.IsLetterOrDigit).Should().BeTrue(); - } + x.Any(char.IsSurrogate).Should().BeFalse(); + x.All(char.IsLetterOrDigit).Should().BeTrue(); + } - [Fact] - public void static_utf16_tests() - { - r.Utf16String().Should().Be("𦊕𡰴ဩਢۥ侀ゞᜡﷴ𠸮𝒾ⶱﹱຂⱪ𝒟𝚪𝒩𝝵ೡཧΐ뢫ⱜੳ𣽇𐨖ਆ𐀼ฏളᄎ𐏈𦵻𐠸𝕋ꡨ𝔇ずరᢔﬣ𐨟𝔚ઐష"); - r.Utf16String().Should().Be("னమወ𡂑ப𐠁ஞ𦂰ઐ𢂍ᬒ𒀓𨴽𝜅𧊆𦑆ආ𝜂ଭ𐀪ಋΊ౦౨ㆳꠁⶺ𝛈𡓎𡯸ᜑ𐁁𝜹લ𩠺ଐ𦕲ﬔჁⶂム𝐾𣭄ງヾ༤𝒪ᙵͼ၅𦛃𩕾ﷸ𝜦ⱶ"); - } + [Fact] + public void static_utf16_tests() + { + r.Utf16String().Should().Be("𦊕𡰴ဩਢۥ侀ゞᜡﷴ𠸮𝒾ⶱﹱຂⱪ𝒟𝚪𝒩𝝵ೡཧΐ뢫ⱜੳ𣽇𐨖ਆ𐀼ฏളᄎ𐏈𦵻𐠸𝕋ꡨ𝔇ずరᢔﬣ𐨟𝔚ઐష"); + r.Utf16String().Should().Be("னమወ𡂑ப𐠁ஞ𦂰ઐ𢂍ᬒ𒀓𨴽𝜅𧊆𦑆ආ𝜂ଭ𐀪ಋΊ౦౨ㆳꠁⶺ𝛈𡓎𡯸ᜑ𐁁𝜹લ𩠺ଐ𦕲ﬔჁⶂム𝐾𣭄ງヾ༤𝒪ᙵͼ၅𦛃𩕾ﷸ𝜦ⱶ"); + } - [Fact] - public void empty_collection_throws_better_exception_message_rather_than_index_out_of_bounds() - { - var x = new int[] { }; + [Fact] + public void empty_collection_throws_better_exception_message_rather_than_index_out_of_bounds() + { + var x = new int[] { }; - Action arrayAction = () => r.ArrayElement(x); - arrayAction.Should().Throw() - .Where(ex => ex.Message.StartsWith("The array is empty. There are no items to select.")); + Action arrayAction = () => r.ArrayElement(x); + arrayAction.Should().Throw() + .Where(ex => ex.Message.StartsWith("The array is empty. There are no items to select.")); - Action listAction = () => r.ListItem(x); - listAction.Should().Throw() - .Where(ex => ex.Message.StartsWith("The list is empty. There are no items to select.")); + Action listAction = () => r.ListItem(x); + listAction.Should().Throw() + .Where(ex => ex.Message.StartsWith("The list is empty. There are no items to select.")); - Action collectionAction = () => r.CollectionItem(x); - collectionAction.Should().Throw() - .Where(ex => ex.Message.StartsWith("The collection is empty. There are no items to select.")); - } + Action collectionAction = () => r.CollectionItem(x); + collectionAction.Should().Throw() + .Where(ex => ex.Message.StartsWith("The collection is empty. There are no items to select.")); } } diff --git a/Source/Bogus.Tests/Rant_Generator.cs b/Source/Bogus.Tests/Rant_Generator.cs index cb5c0d11..82be2f05 100644 --- a/Source/Bogus.Tests/Rant_Generator.cs +++ b/Source/Bogus.Tests/Rant_Generator.cs @@ -8,80 +8,79 @@ using Rant.Resources; using Xunit; -namespace Bogus.Tests +namespace Bogus.Tests; + +public class Rant_Generator { - public class Rant_Generator - { - public const string Package = "Rantionary-3.0.17.rantpkg"; - public const int Seed = 90; + public const string Package = "Rantionary-3.0.17.rantpkg"; + public const int Seed = 90; - private RantEngine rant; - private RNG rng; + private RantEngine rant; + private RNG rng; - public Rant_Generator() - { - rant = new RantEngine(); - rng = new RNG(Seed); + public Rant_Generator() + { + rant = new RantEngine(); + rng = new RNG(Seed); - Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); + Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); - var package = RantPackage.Load(Package); + var package = RantPackage.Load(Package); - rant.LoadPackage(package); - } + rant.LoadPackage(package); + } - [Fact(Skip = "Explicit")] - public void generate_product_reviews() - { - var reviews = new[] - { - "this $product is .", - "I tried to it but got all over it.", - "i use it when i'm in my .", - "My loves to play with it.", - "[vl:ending][ladd:ending;!;!!;!!!;.]The box this comes in is [num:3;5] by [num:5;6] and weights [num:10;20] [lrand:ending]", - "This $product works well. It improves my by a lot.", - "I saw one of these in and I bought one.", - "one of my hobbies is . and when i'm this works great.", - "It only works when I'm .", - "My neighbor has one of these. She works as a and she says it looks .", - "My co-worker has one of these. He says it looks .", - "heard about this on radio, decided to give it a try.", - "[vl:ending][ladd:ending;!;!!;!!!;.]talk about [lrand:ending]" - }; + [Fact(Skip = "Explicit")] + public void generate_product_reviews() + { + var reviews = new[] + { + "this $product is .", + "I tried to it but got all over it.", + "i use it when i'm in my .", + "My loves to play with it.", + "[vl:ending][ladd:ending;!;!!;!!!;.]The box this comes in is [num:3;5] by [num:5;6] and weights [num:10;20] [lrand:ending]", + "This $product works well. It improves my by a lot.", + "I saw one of these in and I bought one.", + "one of my hobbies is . and when i'm this works great.", + "It only works when I'm .", + "My neighbor has one of these. She works as a and she says it looks .", + "My co-worker has one of these. He says it looks .", + "heard about this on radio, decided to give it a try.", + "[vl:ending][ladd:ending;!;!!;!!!;.]talk about [lrand:ending]" + }; - var singles = new[] - { - "This $product, does exactly what it's suppose to do.", - "SoCal cockroaches are unwelcome, crafty, and tenacious. This $product keeps them away.", - "works okay.", - "I saw this on TV and wanted to give it a try.", - "This is a really good $product." - }; + var singles = new[] + { + "This $product, does exactly what it's suppose to do.", + "SoCal cockroaches are unwelcome, crafty, and tenacious. This $product keeps them away.", + "works okay.", + "I saw this on TV and wanted to give it a try.", + "This is a really good $product." + }; - var genReviews = reviews - .Select(rant => RantProgram.CompileString(rant)) - .SelectMany(pgm => - { - return Enumerable.Range(1, 25) - .Select(_ => rant.Do(pgm, rng).Main); - }) - .Concat(singles) - .Distinct() - .ToList(); - Inject("en", "rant", "review", genReviews); - } + var genReviews = reviews + .Select(rant => RantProgram.CompileString(rant)) + .SelectMany(pgm => + { + return Enumerable.Range(1, 25) + .Select(_ => rant.Do(pgm, rng).Main); + }) + .Concat(singles) + .Distinct() + .ToList(); + Inject("en", "rant", "review", genReviews); + } - private void Inject(string locale, string category, string section, List genReviews) - { - var path = $@"..\..\..\Bogus\data_extend\{locale}.locale.json"; - var json = File.ReadAllText(path); - var j = JObject.Parse(json); - if( j[category] is null ) - j[category] = new JObject(); - j[category][section] = JArray.FromObject(genReviews); + private void Inject(string locale, string category, string section, List genReviews) + { + var path = $@"..\..\..\Bogus\data_extend\{locale}.locale.json"; + var json = File.ReadAllText(path); + var j = JObject.Parse(json); + if( j[category] is null ) + j[category] = new JObject(); + j[category][section] = JArray.FromObject(genReviews); - File.WriteAllText(path, j.ToString(Formatting.Indented)); - } + File.WriteAllText(path, j.ToString(Formatting.Indented)); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/RuleSetTests.cs b/Source/Bogus.Tests/RuleSetTests.cs index ec8a0b59..15a24ef5 100644 --- a/Source/Bogus.Tests/RuleSetTests.cs +++ b/Source/Bogus.Tests/RuleSetTests.cs @@ -3,169 +3,168 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests +namespace Bogus.Tests; + +public class RuleSetTests : SeededTest { - public class RuleSetTests : SeededTest + public RuleSetTests() + { + Faker.DefaultStrictMode = false; + } + + public class Customer + { + public int Id { get; set; } + public string Description { get; set; } + public bool GoodCustomer { get; set; } + } + + [Fact] + public void should_be_able_to_create_a_rule_set() + { + var orderIds = 0; + var testCustomers = new Faker() + .RuleSet("Good", + (set) => + { + set.StrictMode(true); + set.RuleFor(c => c.Id, f => orderIds++); + set.RuleFor(c => c.Description, f => f.Lorem.Sentence()); + set.RuleFor(c => c.GoodCustomer, f => true); + }) + .StrictMode(true) + .RuleFor(c => c.Id, f => orderIds++) + //.RuleFor(c => c.Description, f => f.Lorem.Sentence()) + .RuleFor(c => c.GoodCustomer, f => false); + + var results = testCustomers.Generate(5, "Good"); + + results.All(s => s.GoodCustomer).Should().BeTrue(); + + results.Dump(); + } + + [Fact] + public void should_be_able_to_run_two_rules_with_last_one_taking_precedence() + { + var orderIds = 0; + var testCustomers = new Faker() + .RuleSet("Good", + (set) => + { + set.StrictMode(true); + set.RuleFor(c => c.Id, f => orderIds++); + set.RuleFor(c => c.Description, f => f.Lorem.Sentence()); + set.RuleFor(c => c.GoodCustomer, f => true); + }) + .StrictMode(true) + .RuleFor(c => c.Id, f => orderIds++) + .RuleFor(c => c.Description, f => f.Lorem.Sentence()) + .RuleFor(c => c.GoodCustomer, f => false); + + var results = testCustomers.Generate(5, "default,Good"); + + results.All(s => s.GoodCustomer).Should().BeTrue(); + + results.Dump(); + } + + [Fact] + public void should_be_able_to_run_default_ruleset() + { + var orderIds = 0; + var testCustomers = new Faker() + .RuleSet("Good", + (set) => + { + set.StrictMode(true); + set.RuleFor(c => c.Id, f => orderIds++); + set.RuleFor(c => c.Description, f => f.Lorem.Sentence()); + set.RuleFor(c => c.GoodCustomer, f => true); + }) + .StrictMode(true) + .RuleFor(c => c.Id, f => orderIds++) + .RuleFor(c => c.Description, f => f.Lorem.Sentence()) + .RuleFor(c => c.GoodCustomer, f => false); + + var results = testCustomers.Generate(5); + + results.All(s => s.GoodCustomer).Should().BeFalse(); + + results.Dump(); + } + + [Fact] + public void should_throw_error_when_strict_mode_is_set() { - public RuleSetTests() - { - Faker.DefaultStrictMode = false; - } - - public class Customer - { - public int Id { get; set; } - public string Description { get; set; } - public bool GoodCustomer { get; set; } - } - - [Fact] - public void should_be_able_to_create_a_rule_set() - { - var orderIds = 0; - var testCustomers = new Faker() - .RuleSet("Good", - (set) => - { - set.StrictMode(true); - set.RuleFor(c => c.Id, f => orderIds++); - set.RuleFor(c => c.Description, f => f.Lorem.Sentence()); - set.RuleFor(c => c.GoodCustomer, f => true); - }) - .StrictMode(true) - .RuleFor(c => c.Id, f => orderIds++) - //.RuleFor(c => c.Description, f => f.Lorem.Sentence()) - .RuleFor(c => c.GoodCustomer, f => false); - - var results = testCustomers.Generate(5, "Good"); - - results.All(s => s.GoodCustomer).Should().BeTrue(); - - results.Dump(); - } - - [Fact] - public void should_be_able_to_run_two_rules_with_last_one_taking_precedence() - { - var orderIds = 0; - var testCustomers = new Faker() - .RuleSet("Good", - (set) => - { - set.StrictMode(true); - set.RuleFor(c => c.Id, f => orderIds++); - set.RuleFor(c => c.Description, f => f.Lorem.Sentence()); - set.RuleFor(c => c.GoodCustomer, f => true); - }) - .StrictMode(true) - .RuleFor(c => c.Id, f => orderIds++) - .RuleFor(c => c.Description, f => f.Lorem.Sentence()) - .RuleFor(c => c.GoodCustomer, f => false); - - var results = testCustomers.Generate(5, "default,Good"); - - results.All(s => s.GoodCustomer).Should().BeTrue(); - - results.Dump(); - } - - [Fact] - public void should_be_able_to_run_default_ruleset() - { - var orderIds = 0; - var testCustomers = new Faker() - .RuleSet("Good", - (set) => - { - set.StrictMode(true); - set.RuleFor(c => c.Id, f => orderIds++); - set.RuleFor(c => c.Description, f => f.Lorem.Sentence()); - set.RuleFor(c => c.GoodCustomer, f => true); - }) - .StrictMode(true) - .RuleFor(c => c.Id, f => orderIds++) - .RuleFor(c => c.Description, f => f.Lorem.Sentence()) - .RuleFor(c => c.GoodCustomer, f => false); - - var results = testCustomers.Generate(5); - - results.All(s => s.GoodCustomer).Should().BeFalse(); - - results.Dump(); - } - - [Fact] - public void should_throw_error_when_strict_mode_is_set() - { - var orderIds = 0; - var testCustomers = new Faker() - .RuleSet("Good", - (set) => - { - set.StrictMode(true); - set.RuleFor(c => c.Id, f => orderIds++); - set.RuleFor(c => c.GoodCustomer, f => true); - }) - .StrictMode(true) - .RuleFor(c => c.Id, f => orderIds++) - .RuleFor(c => c.Description, f => f.Lorem.Sentence()) - .RuleFor(c => c.GoodCustomer, f => false); - - Action act = () => - { - var goodCustomers = testCustomers.Generate(5, "Good"); - goodCustomers.Dump(); - }; - act.Should().Throw(); - } - - [Fact] - public void should_be_able_to_override_existing_rules() - { - var testCustomers = new Faker() - .RuleSet("Good", - (set) => - { - set.RuleFor(c => c.Description, f => f.Lorem.Sentence()); - set.RuleFor(c => c.Description, f => "overridden"); - }); - - var results = testCustomers.Generate(5, "Good"); - - results.Should().OnlyContain(c => c.Description == "overridden"); - } - - [Fact] - public void should_be_able_to_use_rules_with_ruleset() - { - var testCustomers = new Faker() - .RuleSet("Good", - (set) => - { - set.Rules((f, c) => - { - c.Description = f.Lorem.Sentence(); - c.Description = "overridden"; - }); - }); - - var results = testCustomers.Generate(5, "Good"); - - results.Should().OnlyContain(c => c.Description == "overridden"); - } - - - public class EmptyObject - { - } - - [Fact] - public void can_create_a_fake_object_with_no_props_or_rules() - { - var f = new Faker() - .StrictMode(true); - - f.Generate().Should().NotBeNull(); - } + var orderIds = 0; + var testCustomers = new Faker() + .RuleSet("Good", + (set) => + { + set.StrictMode(true); + set.RuleFor(c => c.Id, f => orderIds++); + set.RuleFor(c => c.GoodCustomer, f => true); + }) + .StrictMode(true) + .RuleFor(c => c.Id, f => orderIds++) + .RuleFor(c => c.Description, f => f.Lorem.Sentence()) + .RuleFor(c => c.GoodCustomer, f => false); + + Action act = () => + { + var goodCustomers = testCustomers.Generate(5, "Good"); + goodCustomers.Dump(); + }; + act.Should().Throw(); + } + + [Fact] + public void should_be_able_to_override_existing_rules() + { + var testCustomers = new Faker() + .RuleSet("Good", + (set) => + { + set.RuleFor(c => c.Description, f => f.Lorem.Sentence()); + set.RuleFor(c => c.Description, f => "overridden"); + }); + + var results = testCustomers.Generate(5, "Good"); + + results.Should().OnlyContain(c => c.Description == "overridden"); + } + + [Fact] + public void should_be_able_to_use_rules_with_ruleset() + { + var testCustomers = new Faker() + .RuleSet("Good", + (set) => + { + set.Rules((f, c) => + { + c.Description = f.Lorem.Sentence(); + c.Description = "overridden"; + }); + }); + + var results = testCustomers.Generate(5, "Good"); + + results.Should().OnlyContain(c => c.Description == "overridden"); + } + + + public class EmptyObject + { + } + + [Fact] + public void can_create_a_fake_object_with_no_props_or_rules() + { + var f = new Faker() + .StrictMode(true); + + f.Generate().Should().NotBeNull(); } } diff --git a/Source/Bogus.Tests/SeededTest.cs b/Source/Bogus.Tests/SeededTest.cs index 5d088f94..16fe54a0 100644 --- a/Source/Bogus.Tests/SeededTest.cs +++ b/Source/Bogus.Tests/SeededTest.cs @@ -3,32 +3,31 @@ using System.Linq; using Xunit; -namespace Bogus.Tests +namespace Bogus.Tests; + +/// +/// Tests deriving from ensures +/// that when xunit runs, that seeded tests run one at a +/// time in the same test collection (without parallelization) +/// since Randomizer.Seed is a static property. +/// +[Collection("Seeded Test")] +public class SeededTest { - /// - /// Tests deriving from ensures - /// that when xunit runs, that seeded tests run one at a - /// time in the same test collection (without parallelization) - /// since Randomizer.Seed is a static property. - /// - [Collection("Seeded Test")] - public class SeededTest + public SeededTest() { - public SeededTest() - { - //set the random gen manually to a seeded value - ResetGlobalSeed(); - } + //set the random gen manually to a seeded value + ResetGlobalSeed(); + } - protected static void ResetGlobalSeed() - { - Randomizer.Seed = new System.Random(3116); - } + protected static void ResetGlobalSeed() + { + Randomizer.Seed = new System.Random(3116); + } - protected IEnumerable Make(int times, Func a) - { - return Enumerable.Range(0, times) - .Select(i => a()).ToArray(); - } + protected IEnumerable Make(int times, Func a) + { + return Enumerable.Range(0, times) + .Select(i => a()).ToArray(); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/StackOverflowQuestions/Question60136934.cs b/Source/Bogus.Tests/StackOverflowQuestions/Question60136934.cs index 04a4b34b..ab042008 100644 --- a/Source/Bogus.Tests/StackOverflowQuestions/Question60136934.cs +++ b/Source/Bogus.Tests/StackOverflowQuestions/Question60136934.cs @@ -3,61 +3,60 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.StackOverflowQuestions +namespace Bogus.Tests.StackOverflowQuestions; + +//https://stackoverflow.com/questions/60136934/generate-a-random-number-of-addresses-each-with-a-unique-type-value-with-bogus-f +public class Question60136934 : SeededTest { - //https://stackoverflow.com/questions/60136934/generate-a-random-number-of-addresses-each-with-a-unique-type-value-with-bogus-f - public class Question60136934 : SeededTest + private Randomizer r; + + enum Foo + { + A, + B, + C, + D + } + + public Question60136934() + { + r = new Randomizer(); + } + + [Fact] + public void pick_subset_of_enum_values_except_c_and_d() + { + var chosen = r.EnumValues(2, Foo.C, Foo.D); + + chosen.Length.Should().Be(2); + chosen[0].Should().Be(Foo.B); + chosen[1].Should().Be(Foo.A); + } + + [Fact] + public void pick_subset_of_enum_values_except_c() + { + var chosen = r.EnumValues(2, exclude: Foo.C); + chosen.Length.Should().Be(2); + chosen[0].Should().Be(Foo.B); + chosen[1].Should().Be(Foo.A); + } + + [Fact] + public void pick_any_two_random_enums() + { + var chosen = r.EnumValues(2); + + chosen.Length.Should().Be(2); + chosen.Should().Equal(Foo.C, Foo.B); + } + + [Theory] + [InlineData(-3)] + [InlineData(9)] + public void pick_invalid_number_of_enums(int count) { - private Randomizer r; - - enum Foo - { - A, - B, - C, - D - } - - public Question60136934() - { - r = new Randomizer(); - } - - [Fact] - public void pick_subset_of_enum_values_except_c_and_d() - { - var chosen = r.EnumValues(2, Foo.C, Foo.D); - - chosen.Length.Should().Be(2); - chosen[0].Should().Be(Foo.B); - chosen[1].Should().Be(Foo.A); - } - - [Fact] - public void pick_subset_of_enum_values_except_c() - { - var chosen = r.EnumValues(2, exclude: Foo.C); - chosen.Length.Should().Be(2); - chosen[0].Should().Be(Foo.B); - chosen[1].Should().Be(Foo.A); - } - - [Fact] - public void pick_any_two_random_enums() - { - var chosen = r.EnumValues(2); - - chosen.Length.Should().Be(2); - chosen.Should().Equal(Foo.C, Foo.B); - } - - [Theory] - [InlineData(-3)] - [InlineData(9)] - public void pick_invalid_number_of_enums(int count) - { - Action act = () => r.EnumValues(count); - act.Should().Throw(); - } + Action act = () => r.EnumValues(count); + act.Should().Throw(); } } diff --git a/Source/Bogus.Tests/StackOverflowQuestions/Question66444118.cs b/Source/Bogus.Tests/StackOverflowQuestions/Question66444118.cs index 9b4846f3..2af1e547 100644 --- a/Source/Bogus.Tests/StackOverflowQuestions/Question66444118.cs +++ b/Source/Bogus.Tests/StackOverflowQuestions/Question66444118.cs @@ -6,60 +6,59 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests.StackOverflowQuestions +namespace Bogus.Tests.StackOverflowQuestions; + +//https://stackoverflow.com/questions/66444118/how-to-use-bogus-faker-with-initialization-properties +public class Question66444118 : SeededTest { - //https://stackoverflow.com/questions/66444118/how-to-use-bogus-faker-with-initialization-properties - public class Question66444118 : SeededTest + [Fact] + public void can_reflect_private_backing_fields_in_fakerT() { - [Fact] - public void can_reflect_private_backing_fields_in_fakerT() - { - var backingFieldBinder = new BackingFieldBinder(); - var fooFaker = new Faker(binder: backingFieldBinder) - .SkipConstructor() - .RuleFor(f => f.Name, f => f.Name.FullName()); + var backingFieldBinder = new BackingFieldBinder(); + var fooFaker = new Faker(binder: backingFieldBinder) + .SkipConstructor() + .RuleFor(f => f.Name, f => f.Name.FullName()); - var foo = fooFaker.Generate(); - foo.Name.Should().NotBeNullOrWhiteSpace(); - } + var foo = fooFaker.Generate(); + foo.Name.Should().NotBeNullOrWhiteSpace(); + } - public class BackingFieldBinder : IBinder + public class BackingFieldBinder : IBinder + { + public Dictionary GetMembers(Type t) { - public Dictionary GetMembers(Type t) - { - var availableFieldsForFakerT = new Dictionary(); - var bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance; - var allMembers = t.GetMembers(bindingFlags); - var allBackingFields = allMembers - .OfType() - .Where(fi => fi.IsPrivate && fi.IsInitOnly) - .Where(fi => fi.Name.EndsWith("__BackingField")) - .ToList(); - - foreach (var backingField in allBackingFields) - { - var fieldName = backingField.Name.Substring(1).Replace(">k__BackingField", ""); - availableFieldsForFakerT.Add(fieldName, backingField); - } - return availableFieldsForFakerT; - } - } + var availableFieldsForFakerT = new Dictionary(); + var bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance; + var allMembers = t.GetMembers(bindingFlags); + var allBackingFields = allMembers + .OfType() + .Where(fi => fi.IsPrivate && fi.IsInitOnly) + .Where(fi => fi.Name.EndsWith("__BackingField")) + .ToList(); - public class Foo - { - public Foo(string name) + foreach (var backingField in allBackingFields) { - this.Name = name; + var fieldName = backingField.Name.Substring(1).Replace(">k__BackingField", ""); + availableFieldsForFakerT.Add(fieldName, backingField); } - public string Name { get; } + return availableFieldsForFakerT; } } - public static class MyExtensionsForFakerT + public class Foo { - public static Faker SkipConstructor(this Faker fakerOfT) where T : class + public Foo(string name) { - return fakerOfT.CustomInstantiator(_ => FormatterServices.GetUninitializedObject(typeof(T)) as T); + this.Name = name; } + public string Name { get; } + } +} + +public static class MyExtensionsForFakerT +{ + public static Faker SkipConstructor(this Faker fakerOfT) where T : class + { + return fakerOfT.CustomInstantiator(_ => FormatterServices.GetUninitializedObject(typeof(T)) as T); } } \ No newline at end of file diff --git a/Source/Bogus.Tests/StrictModeTests.cs b/Source/Bogus.Tests/StrictModeTests.cs index 1c5e705f..4bef8d04 100644 --- a/Source/Bogus.Tests/StrictModeTests.cs +++ b/Source/Bogus.Tests/StrictModeTests.cs @@ -2,114 +2,113 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests +namespace Bogus.Tests; + +public class StrictModeTests : SeededTest { - public class StrictModeTests : SeededTest + [Fact] + public void should_throw_exception_on_incomplete_rules() + { + var testOrders = new Faker() + .StrictMode(true) + .RuleFor(o => o.Quantity, f => f.Random.Number(2, 5)); + + testOrders.Invoking(faker => faker.Generate()) + .Should().Throw(); + } + + [Fact] + public void should_not_throw_exception_on_complete_rule_set() + { + var testOrders = new Faker() + .StrictMode(true) + .Ignore(o => o.LotNumber) + .RuleFor(o => o.Quantity, f => f.Random.Number(2, 5)) + .RuleFor(o => o.Item, f => f.Lorem.Sentence()) + .RuleFor(o => o.OrderId, f => f.Random.Number()); + + testOrders.Invoking(faker => faker.Generate()) + .Should().NotThrow(); + } + + [Fact] + public void cannot_use_rules_with_strictmode() + { + var faker = new Faker() + .Rules((f, o) => + { + o.Quantity = f.Random.Number(1, 4); + o.Item = f.Commerce.Product(); + o.OrderId = 25; + }) + .StrictMode(true); + + Action act = () => faker.AssertConfigurationIsValid(); + act.Should().Throw(); + + var faker2 = new Faker() + .StrictMode(true) + .Rules((f, o) => + { + o.Quantity = f.Random.Number(1, 4); + o.Item = f.Commerce.Product(); + o.OrderId = 25; + }); + + Action act2 = () => faker2.AssertConfigurationIsValid(); + act2.Should().Throw(); + } + + [Fact] + public void cannot_use_rules_with_strictmode_inside_rulesets() + { + const string myset = "myset"; + + var faker = new Faker() + .RuleSet(myset, set => + { + set.Rules((f, o) => + { + o.Quantity = f.Random.Number(1, 4); + o.Item = f.Commerce.Product(); + o.OrderId = 25; + }); + set.StrictMode(true); + }); + + Action act = () => faker.AssertConfigurationIsValid(); + act.Should().Throw(); + + var faker2 = new Faker() + .RuleSet(myset, set => + { + set.StrictMode(true); + set.Rules((f, o) => + { + o.Quantity = f.Random.Number(1, 4); + o.Item = f.Commerce.Product(); + o.OrderId = 25; + }); + }); + + Action act2 = () => faker2.AssertConfigurationIsValid(); + act2.Should().Throw(); + } + + [Fact] + public void strictmode_with_no_rules_should_throw() { - [Fact] - public void should_throw_exception_on_incomplete_rules() - { - var testOrders = new Faker() - .StrictMode(true) - .RuleFor(o => o.Quantity, f => f.Random.Number(2, 5)); - - testOrders.Invoking(faker => faker.Generate()) - .Should().Throw(); - } - - [Fact] - public void should_not_throw_exception_on_complete_rule_set() - { - var testOrders = new Faker() - .StrictMode(true) - .Ignore(o => o.LotNumber) - .RuleFor(o => o.Quantity, f => f.Random.Number(2, 5)) - .RuleFor(o => o.Item, f => f.Lorem.Sentence()) - .RuleFor(o => o.OrderId, f => f.Random.Number()); - - testOrders.Invoking(faker => faker.Generate()) - .Should().NotThrow(); - } - - [Fact] - public void cannot_use_rules_with_strictmode() - { - var faker = new Faker() - .Rules((f, o) => - { - o.Quantity = f.Random.Number(1, 4); - o.Item = f.Commerce.Product(); - o.OrderId = 25; - }) - .StrictMode(true); - - Action act = () => faker.AssertConfigurationIsValid(); - act.Should().Throw(); - - var faker2 = new Faker() - .StrictMode(true) - .Rules((f, o) => - { - o.Quantity = f.Random.Number(1, 4); - o.Item = f.Commerce.Product(); - o.OrderId = 25; - }); - - Action act2 = () => faker2.AssertConfigurationIsValid(); - act2.Should().Throw(); - } - - [Fact] - public void cannot_use_rules_with_strictmode_inside_rulesets() - { - const string myset = "myset"; - - var faker = new Faker() - .RuleSet(myset, set => - { - set.Rules((f, o) => - { - o.Quantity = f.Random.Number(1, 4); - o.Item = f.Commerce.Product(); - o.OrderId = 25; - }); - set.StrictMode(true); - }); - - Action act = () => faker.AssertConfigurationIsValid(); - act.Should().Throw(); - - var faker2 = new Faker() - .RuleSet(myset, set => - { - set.StrictMode(true); - set.Rules((f, o) => - { - o.Quantity = f.Random.Number(1, 4); - o.Item = f.Commerce.Product(); - o.OrderId = 25; - }); - }); - - Action act2 = () => faker2.AssertConfigurationIsValid(); - act2.Should().Throw(); - } - - [Fact] - public void strictmode_with_no_rules_should_throw() - { - var faker = new Faker() - .StrictMode(true); - - Action act = () => faker.Generate(1); - - act.Should().ThrowExactly() - .WithMessage("*Missing Rules*") - .WithMessage("*Validation was called to ensure all properties*") - .WithMessage($"*{nameof(Examples.Order.OrderId)}*") - .WithMessage($"*{nameof(Examples.Order.Item)}*") - .WithMessage($"*{nameof(Examples.Order.Quantity)}*") - .WithMessage($"*{nameof(Examples.Order.LotNumber)}*"); - } + var faker = new Faker() + .StrictMode(true); + + Action act = () => faker.Generate(1); + + act.Should().ThrowExactly() + .WithMessage("*Missing Rules*") + .WithMessage("*Validation was called to ensure all properties*") + .WithMessage($"*{nameof(Examples.Order.OrderId)}*") + .WithMessage($"*{nameof(Examples.Order.Item)}*") + .WithMessage($"*{nameof(Examples.Order.Quantity)}*") + .WithMessage($"*{nameof(Examples.Order.LotNumber)}*"); } } diff --git a/Source/Bogus.Tests/TransliterateTests.cs b/Source/Bogus.Tests/TransliterateTests.cs index b6e26b3c..56e74170 100644 --- a/Source/Bogus.Tests/TransliterateTests.cs +++ b/Source/Bogus.Tests/TransliterateTests.cs @@ -2,67 +2,66 @@ using FluentAssertions; using Xunit; -namespace Bogus.Tests +namespace Bogus.Tests; + +public class TransliterateTests { - public class TransliterateTests + [Fact] + public void Test() { - [Fact] - public void Test() - { - Transliterater.Translate("À").Should().Be("A"); - Transliterater.Translate("ден").Should().Be("MKD"); - Transliterater.Translate("စျ").Should().Be("za"); - } + Transliterater.Translate("À").Should().Be("A"); + Transliterater.Translate("ден").Should().Be("MKD"); + Transliterater.Translate("စျ").Should().Be("za"); + } - [Fact] - public void index_test() - { - Transliterater.Translate("ေါင်ူ").Should().Be("aungu"); - } + [Fact] + public void index_test() + { + Transliterater.Translate("ေါင်ူ").Should().Be("aungu"); + } - [Fact] - public void simple_test() - { - Transliterater.Translate("ာ").Should().Be("a"); - } + [Fact] + public void simple_test() + { + Transliterater.Translate("ာ").Should().Be("a"); + } - [Fact] - public void basic_ru_test() - { - Transliterater.Translate("Анна Фомина").Should().Be("Anna Fomina"); - } + [Fact] + public void basic_ru_test() + { + Transliterater.Translate("Анна Фомина").Should().Be("Anna Fomina"); + } - [Fact] - public void index2_test() - { - Transliterater.Translate("ေါင်ff").Should().Be("aungff"); - } + [Fact] + public void index2_test() + { + Transliterater.Translate("ေါင်ff").Should().Be("aungff"); + } - [Fact] - public void transliterate_with_unknown_langauge_doesnt_throw() - { - Action a = () => Transliterater.Translate("fefefe", "gggg"); - a.Should().NotThrow(); - } + [Fact] + public void transliterate_with_unknown_langauge_doesnt_throw() + { + Action a = () => Transliterater.Translate("fefefe", "gggg"); + a.Should().NotThrow(); + } - [Fact] - public void can_translate_symbol() - { - Transliterater.Translate("♥").Should().Be("love"); - } + [Fact] + public void can_translate_symbol() + { + Transliterater.Translate("♥").Should().Be("love"); + } - [Fact] - public void can_translate_symbol_with_locale() - { - Transliterater.Translate("♥", "es").Should().Be("amor"); - } + [Fact] + public void can_translate_symbol_with_locale() + { + Transliterater.Translate("♥", "es").Should().Be("amor"); + } - [Fact] - public void can_translate_with_langchar_map() - { - Transliterater.Translate("Ä").Should().Be("Ae"); - Transliterater.Translate("Ä", lang: "fi").Should().Be("A"); - Transliterater.Translate("Ä", lang: "hu").Should().Be("A"); - } + [Fact] + public void can_translate_with_langchar_map() + { + Transliterater.Translate("Ä").Should().Be("Ae"); + Transliterater.Translate("Ä", lang: "fi").Should().Be("A"); + Transliterater.Translate("Ä", lang: "hu").Should().Be("A"); } } diff --git a/Source/Bogus.Tests/UniquenessTests.cs b/Source/Bogus.Tests/UniquenessTests.cs index 96b586ab..518da9cf 100644 --- a/Source/Bogus.Tests/UniquenessTests.cs +++ b/Source/Bogus.Tests/UniquenessTests.cs @@ -4,173 +4,172 @@ using Z.ExtensionMethods; using Z.ExtensionMethods.ObjectExtensions; -namespace Bogus.Tests +namespace Bogus.Tests; + +public class UniquenessTests : SeededTest { - public class UniquenessTests : SeededTest + public class User { - public class User - { - public string FirstName { get; set; } - public string LastName { get; set; } - public string Email { get; set; } - public string Username { get; set; } - } + public string FirstName { get; set; } + public string LastName { get; set; } + public string Email { get; set; } + public string Username { get; set; } + } - public UniquenessTests() - { - Faker.GlobalUniqueIndex = -1; - } + public UniquenessTests() + { + Faker.GlobalUniqueIndex = -1; + } - [Fact] - public void every_new_generation_should_have_a_new_unique_index() - { - var faker = new Faker() - .RuleFor(u => u.FirstName, f => f.Person.FirstName) - .RuleFor(u => u.LastName, f => f.Person.LastName) - .RuleFor(u => u.Email, f => f.Person.Email) - .RuleFor(u => u.Username, f => f.IndexGlobal + f.Person.UserName); + [Fact] + public void every_new_generation_should_have_a_new_unique_index() + { + var faker = new Faker() + .RuleFor(u => u.FirstName, f => f.Person.FirstName) + .RuleFor(u => u.LastName, f => f.Person.LastName) + .RuleFor(u => u.Email, f => f.Person.Email) + .RuleFor(u => u.Username, f => f.IndexGlobal + f.Person.UserName); - var fakes = faker.Generate(10); + var fakes = faker.Generate(10); - fakes.Dump(); + fakes.Dump(); - faker.FakerHub.IndexGlobal.Should().Be(9); + faker.FakerHub.IndexGlobal.Should().Be(9); - var values = fakes - .Select(u => u.Username.Left(1).ToInt32()) - .ToArray(); + var values = fakes + .Select(u => u.Username.Left(1).ToInt32()) + .ToArray(); - values.Should().BeEquivalentTo(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); + values.Should().BeEquivalentTo(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); - var morefakes = faker.Generate(3); + var morefakes = faker.Generate(3); - morefakes.Dump(); + morefakes.Dump(); - faker.FakerHub.IndexGlobal.Should().Be(12); - } + faker.FakerHub.IndexGlobal.Should().Be(12); + } - public class Video - { - public int Index { get; set; } - public string VideoId { get; set; } - public string Summary { get; set; } - } + public class Video + { + public int Index { get; set; } + public string VideoId { get; set; } + public string Summary { get; set; } + } - [Fact] - public void should_be_able_to_create_some_hash_ids() - { - var faker = new Faker