diff --git a/src/main/java/org/thejavaguy/javafaker/Address.java b/src/main/java/org/thejavaguy/javafaker/Address.java index e482f9a..8ebf088 100644 --- a/src/main/java/org/thejavaguy/javafaker/Address.java +++ b/src/main/java/org/thejavaguy/javafaker/Address.java @@ -1,117 +1,119 @@ package org.thejavaguy.javafaker; public class Address { - private final Faker faker; + private final Faker faker; - protected Address(Faker faker) { - this.faker = faker; - } + protected Address(Faker faker) { + this.faker = faker; + } - public String streetName() { - return faker.fakeValuesService().resolve("address.street_name", this, faker); - } + public String streetName() { + return faker.fakeValuesService().resolve("address.street_name", this, faker); + } - public String streetAddressNumber() { - return String.valueOf(faker.random().nextInt(1000)); - } + public String streetAddressNumber() { + return String.valueOf(faker.random().nextInt(1000)); + } - public String streetAddress() { - return faker.fakeValuesService().resolve("address.street_address", this, faker); - } + public String streetAddress() { + return faker.fakeValuesService().resolve("address.street_address", this, faker); + } - public String streetAddress(boolean includeSecondary) { - String streetAddress = faker.fakeValuesService().resolve("address.street_address", this, faker); - if (includeSecondary) { - streetAddress = streetAddress + " " + secondaryAddress(); - } - return streetAddress; + public String streetAddress(boolean includeSecondary) { + String streetAddress = faker.fakeValuesService().resolve("address.street_address", this, faker); + if (includeSecondary) { + streetAddress = streetAddress + " " + secondaryAddress(); } + return streetAddress; + } - public String secondaryAddress() { - return faker.numerify(faker.fakeValuesService().resolve("address.secondary_address", this,faker)); - } + public String secondaryAddress() { + return faker.numerify( + faker.fakeValuesService().resolve("address.secondary_address", this, faker)); + } - public String zipCode() { - return faker.bothify(faker.fakeValuesService().resolve("address.postcode", this,faker)); - } + public String zipCode() { + return faker.bothify(faker.fakeValuesService().resolve("address.postcode", this, faker)); + } - public String postcode() { - return faker.bothify(faker.fakeValuesService().resolve("address.postcode", this,faker)); - } + public String postcode() { + return faker.bothify(faker.fakeValuesService().resolve("address.postcode", this, faker)); + } - public String zipCodeByState(String stateAbbr) { - return faker.fakeValuesService().resolve("address.postcode_by_state." + stateAbbr, this, faker); - } + public String zipCodeByState(String stateAbbr) { + return faker.fakeValuesService().resolve("address.postcode_by_state." + stateAbbr, this, faker); + } - public String countyByZipCode(String postCode) { - return faker.fakeValuesService().resolve("address.county_by_postcode." + postCode, this, faker); - } + public String countyByZipCode(String postCode) { + return faker.fakeValuesService().resolve("address.county_by_postcode." + postCode, this, faker); + } - public String streetSuffix() { - return faker.fakeValuesService().resolve("address.street_suffix", this, faker); - } + public String streetSuffix() { + return faker.fakeValuesService().resolve("address.street_suffix", this, faker); + } - public String streetPrefix() { - return faker.fakeValuesService().resolve("address.street_prefix", this, faker); - } + public String streetPrefix() { + return faker.fakeValuesService().resolve("address.street_prefix", this, faker); + } - public String citySuffix() { - return faker.fakeValuesService().resolve("address.city_suffix", this, faker); - } + public String citySuffix() { + return faker.fakeValuesService().resolve("address.city_suffix", this, faker); + } - public String cityPrefix() { - return faker.fakeValuesService().resolve("address.city_prefix", this, faker); - } + public String cityPrefix() { + return faker.fakeValuesService().resolve("address.city_prefix", this, faker); + } - public String city() { - return faker.fakeValuesService().resolve("address.city", this, faker); - } + public String city() { + return faker.fakeValuesService().resolve("address.city", this, faker); + } - public String cityName() { - return faker.fakeValuesService().resolve("address.city_name", this, faker); - } + public String cityName() { + return faker.fakeValuesService().resolve("address.city_name", this, faker); + } - public String state() { - return faker.fakeValuesService().resolve("address.state", this, faker); - } - - public String stateAbbr() { - return faker.fakeValuesService().resolve("address.state_abbr", this, faker); - } - - public String firstName() { - return faker.name().firstName(); - } - - public String lastName() { - return faker.name().lastName(); - } + public String state() { + return faker.fakeValuesService().resolve("address.state", this, faker); + } - public String latitude() { - return String.format("%.8g", (faker.random().nextDouble() * 180) - 90); - } + public String stateAbbr() { + return faker.fakeValuesService().resolve("address.state_abbr", this, faker); + } - public String longitude() { - return String.format("%.8g", (faker.random().nextDouble() * 360) - 180); - } + public String firstName() { + return faker.name().firstName(); + } - public String timeZone() { - return faker.fakeValuesService().resolve("address.time_zone", this, faker); - } + public String lastName() { + return faker.name().lastName(); + } - public String country() { - return faker.fakeValuesService().resolve("address.country", this, faker); - } + public String latitude() { + return String.format("%.8g", (faker.random().nextDouble() * 180) - 90); + } - public String countryCode() { - return faker.fakeValuesService().resolve("address.country_code", this, faker); - } + public String longitude() { + return String.format("%.8g", (faker.random().nextDouble() * 360) - 180); + } - public String buildingNumber() { - return faker.numerify(faker.fakeValuesService().resolve("address.building_number", this, faker)); - } + public String timeZone() { + return faker.fakeValuesService().resolve("address.time_zone", this, faker); + } - public String fullAddress() { - return faker.fakeValuesService().resolve("address.full_address", this, faker); - } + public String country() { + return faker.fakeValuesService().resolve("address.country", this, faker); + } + + public String countryCode() { + return faker.fakeValuesService().resolve("address.country_code", this, faker); + } + + public String buildingNumber() { + return faker.numerify( + faker.fakeValuesService().resolve("address.building_number", this, faker)); + } + + public String fullAddress() { + return faker.fakeValuesService().resolve("address.full_address", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Ancient.java b/src/main/java/org/thejavaguy/javafaker/Ancient.java index 1b6a4b8..85a97b5 100644 --- a/src/main/java/org/thejavaguy/javafaker/Ancient.java +++ b/src/main/java/org/thejavaguy/javafaker/Ancient.java @@ -2,25 +2,25 @@ public class Ancient { - private final Faker faker; + private final Faker faker; - protected Ancient(Faker faker) { - this.faker = faker; - } + protected Ancient(Faker faker) { + this.faker = faker; + } - public String god() { - return faker.resolve("ancient.god"); - } + public String god() { + return faker.resolve("ancient.god"); + } - public String primordial() { - return faker.resolve("ancient.primordial"); - } + public String primordial() { + return faker.resolve("ancient.primordial"); + } - public String titan() { - return faker.resolve("ancient.titan"); - } + public String titan() { + return faker.resolve("ancient.titan"); + } - public String hero() { - return faker.resolve("ancient.hero"); - } + public String hero() { + return faker.resolve("ancient.hero"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Animal.java b/src/main/java/org/thejavaguy/javafaker/Animal.java index da7cd5b..d2d0ab5 100644 --- a/src/main/java/org/thejavaguy/javafaker/Animal.java +++ b/src/main/java/org/thejavaguy/javafaker/Animal.java @@ -1,13 +1,13 @@ package org.thejavaguy.javafaker; public class Animal { - private final Faker faker; + private final Faker faker; - protected Animal(Faker faker) { - this.faker = faker; - } + protected Animal(Faker faker) { + this.faker = faker; + } - public String name() { - return faker.fakeValuesService().resolve("creature.animal.name", this, faker); - } + public String name() { + return faker.fakeValuesService().resolve("creature.animal.name", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/App.java b/src/main/java/org/thejavaguy/javafaker/App.java index d760590..3af8570 100644 --- a/src/main/java/org/thejavaguy/javafaker/App.java +++ b/src/main/java/org/thejavaguy/javafaker/App.java @@ -1,21 +1,21 @@ package org.thejavaguy.javafaker; public class App { - private final Faker faker; + private final Faker faker; - protected App(Faker faker) { - this.faker = faker; - } + protected App(Faker faker) { + this.faker = faker; + } - public String name() { - return faker.fakeValuesService().resolve("app.name", this, faker); - } + public String name() { + return faker.fakeValuesService().resolve("app.name", this, faker); + } - public String version() { - return faker.numerify(faker.fakeValuesService().resolve("app.version", this, faker)); - } + public String version() { + return faker.numerify(faker.fakeValuesService().resolve("app.version", this, faker)); + } - public String author() { - return faker.fakeValuesService().resolve("app.author", this, faker); - } + public String author() { + return faker.fakeValuesService().resolve("app.author", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/AquaTeenHungerForce.java b/src/main/java/org/thejavaguy/javafaker/AquaTeenHungerForce.java index 1201bf2..3316f7e 100644 --- a/src/main/java/org/thejavaguy/javafaker/AquaTeenHungerForce.java +++ b/src/main/java/org/thejavaguy/javafaker/AquaTeenHungerForce.java @@ -2,14 +2,13 @@ public class AquaTeenHungerForce { - private final Faker faker; + private final Faker faker; - protected AquaTeenHungerForce(Faker faker) { - this.faker = faker; - } - - public String character() { - return faker.fakeValuesService().resolve("aqua_teen_hunger_force.character", this, faker); - } + protected AquaTeenHungerForce(Faker faker) { + this.faker = faker; + } + public String character() { + return faker.fakeValuesService().resolve("aqua_teen_hunger_force.character", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Artist.java b/src/main/java/org/thejavaguy/javafaker/Artist.java index 3ee3337..7845fd5 100644 --- a/src/main/java/org/thejavaguy/javafaker/Artist.java +++ b/src/main/java/org/thejavaguy/javafaker/Artist.java @@ -2,13 +2,13 @@ public class Artist { - private final Faker faker; + private final Faker faker; - protected Artist(Faker faker) { - this.faker = faker; - } + protected Artist(Faker faker) { + this.faker = faker; + } - public String name() { - return faker.fakeValuesService().fetchString("artist.names"); - } + public String name() { + return faker.fakeValuesService().fetchString("artist.names"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Avatar.java b/src/main/java/org/thejavaguy/javafaker/Avatar.java index 69201ee..116018f 100644 --- a/src/main/java/org/thejavaguy/javafaker/Avatar.java +++ b/src/main/java/org/thejavaguy/javafaker/Avatar.java @@ -1,15 +1,15 @@ package org.thejavaguy.javafaker; public class Avatar { - private final Faker faker; - private final String baseUrl; + private final Faker faker; + private final String baseUrl; - protected Avatar(Faker faker) { - this.faker = faker; - this.baseUrl = "https://s3.amazonaws.com/uifaces/faces/twitter/"; - } + protected Avatar(Faker faker) { + this.faker = faker; + this.baseUrl = "https://s3.amazonaws.com/uifaces/faces/twitter/"; + } - public String image() { - return baseUrl + faker.fakeValuesService().resolve("internet.avatar", this, faker); - } + public String image() { + return baseUrl + faker.fakeValuesService().resolve("internet.avatar", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Aviation.java b/src/main/java/org/thejavaguy/javafaker/Aviation.java index bc72d80..7eaa239 100644 --- a/src/main/java/org/thejavaguy/javafaker/Aviation.java +++ b/src/main/java/org/thejavaguy/javafaker/Aviation.java @@ -1,36 +1,31 @@ package org.thejavaguy.javafaker; -/** - * Generates aviation related strings. - */ +/** Generates aviation related strings. */ public class Aviation { - private final Faker faker; + private final Faker faker; - protected Aviation(Faker faker) { - this.faker = faker; - } + protected Aviation(Faker faker) { + this.faker = faker; + } - /** - * @return some aircraft name/model/make e.g. "An-2". - */ - public String aircraft() { - return faker.fakeValuesService().fetchString("aviation.aircraft"); - } + /** + * @return some aircraft name/model/make e.g. "An-2". + */ + public String aircraft() { + return faker.fakeValuesService().fetchString("aviation.aircraft"); + } - /** - * Returns an airport ICAO code. - * See also: https://en.wikipedia.org/wiki/List_of_airports_by_ICAO_code:_A - */ - public String airport() { - return faker.fakeValuesService().fetchString("aviation.airport"); - } + /** + * Returns an airport ICAO code. See also: + * https://en.wikipedia.org/wiki/List_of_airports_by_ICAO_code:_A + */ + public String airport() { + return faker.fakeValuesService().fetchString("aviation.airport"); + } - /** - * Provides a METAR weather report. - * Have a look at https://en.wikipedia.org/wiki/METAR - */ - public String METAR() { - return faker.fakeValuesService().fetchString("aviation.metar"); - } + /** Provides a METAR weather report. Have a look at https://en.wikipedia.org/wiki/METAR */ + public String METAR() { + return faker.fakeValuesService().fetchString("aviation.metar"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/BackToTheFuture.java b/src/main/java/org/thejavaguy/javafaker/BackToTheFuture.java index e96e68e..8ea33af 100644 --- a/src/main/java/org/thejavaguy/javafaker/BackToTheFuture.java +++ b/src/main/java/org/thejavaguy/javafaker/BackToTheFuture.java @@ -1,21 +1,21 @@ package org.thejavaguy.javafaker; public class BackToTheFuture { - private final Faker faker; + private final Faker faker; - protected BackToTheFuture(Faker faker) { - this.faker = faker; - } + protected BackToTheFuture(Faker faker) { + this.faker = faker; + } - public String character() { - return faker.resolve("back_to_the_future.characters"); - } + public String character() { + return faker.resolve("back_to_the_future.characters"); + } - public String date() { - return faker.resolve("back_to_the_future.dates"); - } + public String date() { + return faker.resolve("back_to_the_future.dates"); + } - public String quote() { - return faker.resolve("back_to_the_future.quotes"); - } + public String quote() { + return faker.resolve("back_to_the_future.quotes"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Barcode.java b/src/main/java/org/thejavaguy/javafaker/Barcode.java index 96121c1..8f02dcc 100644 --- a/src/main/java/org/thejavaguy/javafaker/Barcode.java +++ b/src/main/java/org/thejavaguy/javafaker/Barcode.java @@ -2,21 +2,21 @@ public class Barcode { - private final Faker faker; + private final Faker faker; - public Barcode(Faker faker) { - this.faker = faker; - } + public Barcode(Faker faker) { + this.faker = faker; + } - public String type() { - return faker.resolve("barcode.types"); - } + public String type() { + return faker.resolve("barcode.types"); + } - public String data(){ - return faker.resolve("barcode.datas"); - } + public String data() { + return faker.resolve("barcode.datas"); + } - public String typeAndData(){ - return faker.resolve("barcode.typeAndData"); - } + public String typeAndData() { + return faker.resolve("barcode.typeAndData"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Basketball.java b/src/main/java/org/thejavaguy/javafaker/Basketball.java index d630701..b989e0d 100644 --- a/src/main/java/org/thejavaguy/javafaker/Basketball.java +++ b/src/main/java/org/thejavaguy/javafaker/Basketball.java @@ -2,48 +2,55 @@ /** * Generate random components of basketall game, e.g. teams, coaches, positions and players. + * * @author unknown and irakatz */ public class Basketball { - private final Faker faker; + private final Faker faker; - /** - * Create a constructor for Basketball. - * @param faker The Faker instance for generating random, different kinds of disease, e.g. the internal disease. - */ - protected Basketball(Faker faker) { - this.faker = faker; - } + /** + * Create a constructor for Basketball. + * + * @param faker The Faker instance for generating random, different kinds of disease, e.g. the + * internal disease. + */ + protected Basketball(Faker faker) { + this.faker = faker; + } - /** - * Generate random basketball teams - * @return Basketball teams - */ - public String teams() { - return faker.fakeValuesService().resolve("basketball.teams", this, faker); - } + /** + * Generate random basketball teams + * + * @return Basketball teams + */ + public String teams() { + return faker.fakeValuesService().resolve("basketball.teams", this, faker); + } - /** - * Generate random coaches in basketball game - * @return Basketball coaches - */ - public String coaches() { - return faker.fakeValuesService().resolve("basketball.coaches", this, faker); - } + /** + * Generate random coaches in basketball game + * + * @return Basketball coaches + */ + public String coaches() { + return faker.fakeValuesService().resolve("basketball.coaches", this, faker); + } - /** - * Generate random positions in basketball game - * @return Basketball positions - */ - public String positions() { - return faker.fakeValuesService().resolve("basketball.positions", this, faker); - } + /** + * Generate random positions in basketball game + * + * @return Basketball positions + */ + public String positions() { + return faker.fakeValuesService().resolve("basketball.positions", this, faker); + } - /** - * Generate random basketball players - * @return Basketball players - */ - public String players() { - return faker.fakeValuesService().resolve("basketball.players", this, faker); - } + /** + * Generate random basketball players + * + * @return Basketball players + */ + public String players() { + return faker.fakeValuesService().resolve("basketball.players", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Beer.java b/src/main/java/org/thejavaguy/javafaker/Beer.java index 2d47b9a..8218f35 100644 --- a/src/main/java/org/thejavaguy/javafaker/Beer.java +++ b/src/main/java/org/thejavaguy/javafaker/Beer.java @@ -1,29 +1,29 @@ package org.thejavaguy.javafaker; public class Beer { - private final Faker faker; + private final Faker faker; - protected Beer(Faker faker) { - this.faker = faker; - } + protected Beer(Faker faker) { + this.faker = faker; + } - public String name() { - return faker.fakeValuesService().resolve("beer.name", this, faker); - } + public String name() { + return faker.fakeValuesService().resolve("beer.name", this, faker); + } - public String style() { - return faker.fakeValuesService().resolve("beer.style", this, faker); - } + public String style() { + return faker.fakeValuesService().resolve("beer.style", this, faker); + } - public String hop() { - return faker.fakeValuesService().resolve("beer.hop", this, faker); - } + public String hop() { + return faker.fakeValuesService().resolve("beer.hop", this, faker); + } - public String yeast() { - return faker.fakeValuesService().resolve("beer.yeast", this, faker); - } + public String yeast() { + return faker.fakeValuesService().resolve("beer.yeast", this, faker); + } - public String malt() { - return faker.fakeValuesService().resolve("beer.malt", this, faker); - } + public String malt() { + return faker.fakeValuesService().resolve("beer.malt", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/BojackHorseman.java b/src/main/java/org/thejavaguy/javafaker/BojackHorseman.java index 0fc2157..67ec5f1 100644 --- a/src/main/java/org/thejavaguy/javafaker/BojackHorseman.java +++ b/src/main/java/org/thejavaguy/javafaker/BojackHorseman.java @@ -2,42 +2,45 @@ /** * Generate random parts in BojackHorseman. + * * @author unknown and irakatz */ - public class BojackHorseman { - private final Faker faker; - - /** - * Create a constructor for BojackHorseman. - * @param faker The Faker instance for generating random parts in BojackHorseman. - */ - protected BojackHorseman(Faker faker) { - this.faker = faker; - } + private final Faker faker; - /** - * Generate random character's name in BojackHorseman. - * @return Characters in BojackHorseman - */ - public String characters() { - return faker.fakeValuesService().resolve("bojack_horseman.characters", this, faker); - } + /** + * Create a constructor for BojackHorseman. + * + * @param faker The Faker instance for generating random parts in BojackHorseman. + */ + protected BojackHorseman(Faker faker) { + this.faker = faker; + } - /** - * Generate random quotes in BojackHorseman. - * @return Quotes in BojackHorseman - */ - public String quotes() { - return faker.fakeValuesService().resolve("bojack_horseman.quotes", this, faker); - } + /** + * Generate random character's name in BojackHorseman. + * + * @return Characters in BojackHorseman + */ + public String characters() { + return faker.fakeValuesService().resolve("bojack_horseman.characters", this, faker); + } - /** - * Generate random tongue twisters in BojackHorseman. - * @return Tongue twisters in BojackHorseman - */ - public String tongueTwisters() { - return faker.fakeValuesService().resolve("bojack_horseman.tongue_twisters", this, faker); - } + /** + * Generate random quotes in BojackHorseman. + * + * @return Quotes in BojackHorseman + */ + public String quotes() { + return faker.fakeValuesService().resolve("bojack_horseman.quotes", this, faker); + } + /** + * Generate random tongue twisters in BojackHorseman. + * + * @return Tongue twisters in BojackHorseman + */ + public String tongueTwisters() { + return faker.fakeValuesService().resolve("bojack_horseman.tongue_twisters", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Book.java b/src/main/java/org/thejavaguy/javafaker/Book.java index 2c0bf56..277289c 100644 --- a/src/main/java/org/thejavaguy/javafaker/Book.java +++ b/src/main/java/org/thejavaguy/javafaker/Book.java @@ -1,25 +1,25 @@ package org.thejavaguy.javafaker; public class Book { - private final Faker faker; + private final Faker faker; - protected Book(Faker faker) { - this.faker = faker; - } + protected Book(Faker faker) { + this.faker = faker; + } - public String author() { - return faker.fakeValuesService().resolve("book.author", this, faker); - } + public String author() { + return faker.fakeValuesService().resolve("book.author", this, faker); + } - public String title() { - return faker.fakeValuesService().resolve("book.title", this, faker); - } + public String title() { + return faker.fakeValuesService().resolve("book.title", this, faker); + } - public String publisher() { - return faker.fakeValuesService().resolve("book.publisher", this, faker); - } + public String publisher() { + return faker.fakeValuesService().resolve("book.publisher", this, faker); + } - public String genre() { - return faker.fakeValuesService().resolve("book.genre", this, faker); - } + public String genre() { + return faker.fakeValuesService().resolve("book.genre", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Bool.java b/src/main/java/org/thejavaguy/javafaker/Bool.java index f7a66c5..730ab4e 100644 --- a/src/main/java/org/thejavaguy/javafaker/Bool.java +++ b/src/main/java/org/thejavaguy/javafaker/Bool.java @@ -1,13 +1,13 @@ package org.thejavaguy.javafaker; public class Bool { - private final Faker faker; + private final Faker faker; - protected Bool(Faker faker) { - this.faker = faker; - } + protected Bool(Faker faker) { + this.faker = faker; + } - public boolean bool() { - return faker.random().nextBoolean(); - } + public boolean bool() { + return faker.random().nextBoolean(); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Buffy.java b/src/main/java/org/thejavaguy/javafaker/Buffy.java index ad4cce4..2917d14 100644 --- a/src/main/java/org/thejavaguy/javafaker/Buffy.java +++ b/src/main/java/org/thejavaguy/javafaker/Buffy.java @@ -1,30 +1,29 @@ package org.thejavaguy.javafaker; public class Buffy { - private final Faker faker; + private final Faker faker; - protected Buffy(Faker faker) { - this.faker = faker; - } + protected Buffy(Faker faker) { + this.faker = faker; + } - public String characters() { - return faker.fakeValuesService().resolve("buffy.characters", this, faker); - } + public String characters() { + return faker.fakeValuesService().resolve("buffy.characters", this, faker); + } - public String quotes() { - return faker.fakeValuesService().resolve("buffy.quotes", this, faker); - } + public String quotes() { + return faker.fakeValuesService().resolve("buffy.quotes", this, faker); + } - public String celebrities() { - return faker.fakeValuesService().resolve("buffy.celebrities", this, faker); - } + public String celebrities() { + return faker.fakeValuesService().resolve("buffy.celebrities", this, faker); + } - public String bigBads() { - return faker.fakeValuesService().resolve("buffy.big_bads", this, faker); - } - - public String episodes() { - return faker.fakeValuesService().resolve("buffy.episodes", this, faker); - } + public String bigBads() { + return faker.fakeValuesService().resolve("buffy.big_bads", this, faker); + } + public String episodes() { + return faker.fakeValuesService().resolve("buffy.episodes", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Business.java b/src/main/java/org/thejavaguy/javafaker/Business.java index 217ddb5..8583647 100644 --- a/src/main/java/org/thejavaguy/javafaker/Business.java +++ b/src/main/java/org/thejavaguy/javafaker/Business.java @@ -2,21 +2,21 @@ public class Business { - private final Faker faker; + private final Faker faker; - protected Business(Faker faker) { - this.faker = faker; - } + protected Business(Faker faker) { + this.faker = faker; + } - public String creditCardNumber() { - return faker.fakeValuesService().resolve("business.credit_card_numbers", this, faker); - } + public String creditCardNumber() { + return faker.fakeValuesService().resolve("business.credit_card_numbers", this, faker); + } - public String creditCardType() { - return faker.fakeValuesService().resolve("business.credit_card_types", this, faker); - } + public String creditCardType() { + return faker.fakeValuesService().resolve("business.credit_card_types", this, faker); + } - public String creditCardExpiry() { - return faker.fakeValuesService().resolve("business.credit_card_expiry_dates", this, faker); - } + public String creditCardExpiry() { + return faker.fakeValuesService().resolve("business.credit_card_expiry_dates", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Cat.java b/src/main/java/org/thejavaguy/javafaker/Cat.java index 25aafca..795812a 100644 --- a/src/main/java/org/thejavaguy/javafaker/Cat.java +++ b/src/main/java/org/thejavaguy/javafaker/Cat.java @@ -2,21 +2,21 @@ public class Cat { - private final Faker faker; + private final Faker faker; - protected Cat(Faker faker) { - this.faker = faker; - } + protected Cat(Faker faker) { + this.faker = faker; + } - public String name() { - return faker.fakeValuesService().resolve("creature.cat.name", this, faker); - } + public String name() { + return faker.fakeValuesService().resolve("creature.cat.name", this, faker); + } - public String breed() { - return faker.fakeValuesService().resolve("creature.cat.breed", this, faker); - } + public String breed() { + return faker.fakeValuesService().resolve("creature.cat.breed", this, faker); + } - public String registry() { - return faker.fakeValuesService().resolve("creature.cat.registry", this, faker); - } + public String registry() { + return faker.fakeValuesService().resolve("creature.cat.registry", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/ChuckNorris.java b/src/main/java/org/thejavaguy/javafaker/ChuckNorris.java index 3825e3e..7cff9bf 100644 --- a/src/main/java/org/thejavaguy/javafaker/ChuckNorris.java +++ b/src/main/java/org/thejavaguy/javafaker/ChuckNorris.java @@ -1,13 +1,13 @@ package org.thejavaguy.javafaker; public class ChuckNorris { - private final Faker faker; + private final Faker faker; - protected ChuckNorris(Faker faker) { - this.faker = faker; - } + protected ChuckNorris(Faker faker) { + this.faker = faker; + } - public String fact() { - return faker.fakeValuesService().resolve("chuck_norris.fact", this, faker); - } + public String fact() { + return faker.fakeValuesService().resolve("chuck_norris.fact", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Code.java b/src/main/java/org/thejavaguy/javafaker/Code.java index 51d073f..94365ae 100644 --- a/src/main/java/org/thejavaguy/javafaker/Code.java +++ b/src/main/java/org/thejavaguy/javafaker/Code.java @@ -4,109 +4,110 @@ import org.apache.commons.lang3.ArrayUtils; -/** - * ISBN Rules : https://en.wikipedia.org/wiki/International_Standard_Book_Number - */ +/** ISBN Rules : https://en.wikipedia.org/wiki/International_Standard_Book_Number */ public class Code { - private final Faker faker; - - protected Code(Faker faker) { - this.faker = faker; - } - - /** - * This can be overridden by specifying - * - * code: - * isbn_gs1: "some expression" - * - * in the appropriate yml file. - * @return a GS1 code for an ISBN13, currently is only 978 and 979 - */ - public String isbnGs1() { - return faker.regexify("978|979"); - } - /** - * This can be overridden by specifying - * - * code: - * isbn_group: "some expression" - * - * in the appropriate yml file. - * @return an ISBN group number - */ - public String isbnGroup() { - return faker.regexify("[0-1]"); - } - - /** - * This can be overridden by specifying - * - * code: - * isbn_registrant: "some expression" - * - * in the appropriate yml file. - * @return an ISBN registrant 'element' with separator - */ - public String isbnRegistrant() { - int ct = faker.random().nextInt(6) + 1; - switch (ct) { - case 6: - return faker.number().numberBetween(0,1) + faker.number().digit() + "-" + faker.number().digits(6); - case 5: - return faker.number().numberBetween(200,699) + "-" + faker.number().digits(5); - case 4: - return faker.number().numberBetween(7000,8499) + "-" + faker.number().digits(4); - case 3: - return faker.number().numberBetween(85000,89999) + "-" + faker.number().digits(3); - case 2: - return faker.number().numberBetween(900000,949999) + "-" + faker.number().digits(2); - case 1: - return faker.number().numberBetween(9500000,9999999) + "-" + faker.number().digits(1); - default: - throw new IllegalStateException("Invalid random " + ct); - } - } - - /** - * @return a valid ISBN10 number with no separators (ex. 9604250590) - */ - public String isbn10() { - return isbn10(false); - } - - /** - * @param separator true if you want separators returned, false otherwise - * @return a valid ISBN10 number with or without separators (ex. 9604250590, 960-425-059-0) - */ - public String isbn10(boolean separator) { - // The registration group identifier is a 1- to 5-digit number - final StringBuilder isbn10 = new StringBuilder() + private final Faker faker; + + protected Code(Faker faker) { + this.faker = faker; + } + + /** + * This can be overridden by specifying + * code: + * isbn_gs1: "some expression" + * in the appropriate yml file. + * + * @return a GS1 code for an ISBN13, currently is only 978 and 979 + */ + public String isbnGs1() { + return faker.regexify("978|979"); + } + + /** + * This can be overridden by specifying + * code: + * isbn_group: "some expression" + * in the appropriate yml file. + * + * @return an ISBN group number + */ + public String isbnGroup() { + return faker.regexify("[0-1]"); + } + + /** + * This can be overridden by specifying + * code: + * isbn_registrant: "some expression" + * in the appropriate yml file. + * + * @return an ISBN registrant 'element' with separator + */ + public String isbnRegistrant() { + int ct = faker.random().nextInt(6) + 1; + switch (ct) { + case 6: + return faker.number().numberBetween(0, 1) + + faker.number().digit() + + "-" + + faker.number().digits(6); + case 5: + return faker.number().numberBetween(200, 699) + "-" + faker.number().digits(5); + case 4: + return faker.number().numberBetween(7000, 8499) + "-" + faker.number().digits(4); + case 3: + return faker.number().numberBetween(85000, 89999) + "-" + faker.number().digits(3); + case 2: + return faker.number().numberBetween(900000, 949999) + "-" + faker.number().digits(2); + case 1: + return faker.number().numberBetween(9500000, 9999999) + "-" + faker.number().digits(1); + default: + throw new IllegalStateException("Invalid random " + ct); + } + } + + /** + * @return a valid ISBN10 number with no separators (ex. 9604250590) + */ + public String isbn10() { + return isbn10(false); + } + + /** + * @param separator true if you want separators returned, false otherwise + * @return a valid ISBN10 number with or without separators (ex. 9604250590, 960-425-059-0) + */ + public String isbn10(boolean separator) { + // The registration group identifier is a 1- to 5-digit number + final StringBuilder isbn10 = + new StringBuilder() .append(faker.expression("#{code.isbn_group}")) .append('-') .append(faker.expression("#{code.isbn_registrant}")) .append('-'); - final int checkDigit = isbn10CheckDigit(isbn10); - isbn10.append(checkDigit != 10 ? checkDigit : "X"); - return separator ? isbn10.toString() : stripIsbnSeparator(isbn10); - } - - /** - * @return a valid ISBN13 number with no separators (ex. 9789604250590) - */ - public String isbn13() { - return isbn13(false); - } - - /** - * @param separator true if you want separators returned, false otherwise - * @return a valid ISBN13 number with or without separators (ex. 9789604250590, 978-960-425-059-0) - */ - public String isbn13(boolean separator) { - // The registration group identifier is a 1- to 5-digit number - final StringBuilder isbn13 = new StringBuilder() + final int checkDigit = isbn10CheckDigit(isbn10); + isbn10.append(checkDigit != 10 ? checkDigit : "X"); + return separator ? isbn10.toString() : stripIsbnSeparator(isbn10); + } + + /** + * @return a valid ISBN13 number with no separators (ex. 9789604250590) + */ + public String isbn13() { + return isbn13(false); + } + + /** + * @param separator true if you want separators returned, false otherwise + * @return a valid ISBN13 number with or without separators (ex. 9789604250590, 978-960-425-059-0) + */ + public String isbn13(boolean separator) { + // The registration group identifier is a 1- to 5-digit number + final StringBuilder isbn13 = + new StringBuilder() .append(faker.expression("#{code.isbn_gs1}")) .append('-') .append(faker.expression("#{code.isbn_group}")) @@ -114,118 +115,119 @@ public String isbn13(boolean separator) { .append(faker.expression("#{code.isbn_registrant}")) .append('-'); - final int checkDigit = isbn13CheckDigit(isbn13); - isbn13.append(checkDigit); - return separator ? isbn13.toString() : stripIsbnSeparator(isbn13); + final int checkDigit = isbn13CheckDigit(isbn13); + isbn13.append(checkDigit); + return separator ? isbn13.toString() : stripIsbnSeparator(isbn13); + } + + private int isbn10CheckDigit(CharSequence t) { + String value = stripIsbnSeparator(t); + int sum = 0; + for (int i = 0; i < value.length(); i++) { + sum += ((i + 1) * toInt(value.substring(i, i + 1))); } + return sum % 11; + } - private int isbn10CheckDigit(CharSequence t) { - String value = stripIsbnSeparator(t); - int sum = 0; - for (int i = 0; i < value.length(); i++) { - sum += ((i + 1) * toInt(value.substring(i, i + 1))); - } - return sum % 11; + private int isbn13CheckDigit(CharSequence t) { + String value = stripIsbnSeparator(t); + int sum = 0; + int multiplier = 0; + for (int i = 0; i < value.length(); i++) { + multiplier = i % 2 == 0 ? 1 : 3; + sum += multiplier * toInt(value.subSequence(i, i + 1).toString()); } - private int isbn13CheckDigit(CharSequence t) { - String value = stripIsbnSeparator(t); - int sum = 0; - int multiplier = 0; - for (int i = 0; i < value.length(); i++) { - multiplier = i % 2 == 0 ? 1 : 3; - sum += multiplier * toInt(value.subSequence(i, i + 1).toString()); - } + return (10 - sum % 10) % 10; + } - return (10 - sum % 10) % 10; - } + private String stripIsbnSeparator(CharSequence t) { + return t.toString().replaceAll("-", ""); + } - private String stripIsbnSeparator(CharSequence t) { - return t.toString().replaceAll("-",""); - } + public String asin() { + return faker.resolve("code.asin"); + } - public String asin() { - return faker.resolve("code.asin"); - } + public String imei() { + char[] str = new char[15]; + int len = str.length; - public String imei() { - char[] str = new char[15]; - int len = str.length; + // Fill in the first two values of the string based with the specified prefix. + String arr = faker.options().option(REPORTING_BODY_IDENTIFIERS); + str[0] = arr.charAt(0); + str[1] = arr.charAt(1); - // Fill in the first two values of the string based with the specified prefix. - String arr = faker.options().option(REPORTING_BODY_IDENTIFIERS); - str[0] = arr.charAt(0); - str[1] = arr.charAt(1); + // Fill all the remaining numbers except for the last one with random values. + for (int i = 2; i < len - 1; i++) { + str[i] = Character.forDigit(faker.number().numberBetween(0, 9), 10); + } - // Fill all the remaining numbers except for the last one with random values. - for (int i=2; i < len - 1; i++) { - str[i] = Character.forDigit(faker.number().numberBetween(0, 9), 10); - } + // Calculate the Luhn checksum of the values thus far + int lenOffset = (len + 1) % 2; + int t = 0; + int sum = 0; + for (int i = 0; i < len - 1; i++) { + if ((i + lenOffset) % 2 != 0) { + t = Character.getNumericValue(str[i]) * 2; - // Calculate the Luhn checksum of the values thus far - int lenOffset = (len + 1) % 2; - int t = 0; - int sum = 0; - for (int i = 0; i < len - 1; i++) { - if ((i + lenOffset) % 2 != 0) { - t = Character.getNumericValue(str[i]) * 2; - - if (t > 9) { - t -= 9; - } - - sum += t; - } else { - sum += Character.getNumericValue(str[i]); - } + if (t > 9) { + t -= 9; } - // Choose the last digit so that it causes the entire string to pass the checksum. - str[len - 1] = Character.forDigit(((10 - (sum % 10)) % 10), 10); - - return new String(str); + sum += t; + } else { + sum += Character.getNumericValue(str[i]); + } } - private static final String [] REPORTING_BODY_IDENTIFIERS - = {"01", "10", "30", "33", "35", "44", "45", "49", "50", "51", "52", "53", "54", "86", "91", "98", "99"}; + // Choose the last digit so that it causes the entire string to pass the checksum. + str[len - 1] = Character.forDigit(((10 - (sum % 10)) % 10), 10); - public String ean8() { - return gtin8(); - } + return new String(str); + } - public String gtin8() { - char[] values = faker.regexify("\\d{7}").toCharArray(); - int sum = 0; - for (int i = 0; i < values.length; i++) { - sum += Character.getNumericValue(values[i]) * GTIN_8_CHECK_DIGITS[i]; - } - int checkDigit = 10 - sum % 10; - if (checkDigit == 10) { - return new String(ArrayUtils.add(values, Character.forDigit(0, 10))); - } else { - return new String(ArrayUtils.add(values, Character.forDigit(checkDigit, 10))); - } - } + private static final String[] REPORTING_BODY_IDENTIFIERS = { + "01", "10", "30", "33", "35", "44", "45", "49", "50", "51", "52", "53", "54", "86", "91", "98", + "99" + }; - public String ean13() { - return gtin13(); - } + public String ean8() { + return gtin8(); + } - public String gtin13() { - char[] values = faker.regexify("\\d{12}").toCharArray(); - int sum = 0; - for (int i = 0; i < values.length; i++) { - sum += Character.getNumericValue(values[i]) * GTIN_13_CHECK_DIGITS[i]; - } - int checkDigit = 10 - sum % 10; - if (checkDigit == 10) { - return new String(ArrayUtils.add(values, Character.forDigit(0, 10))); - } else { - return new String(ArrayUtils.add(values, Character.forDigit(checkDigit, 10))); - } + public String gtin8() { + char[] values = faker.regexify("\\d{7}").toCharArray(); + int sum = 0; + for (int i = 0; i < values.length; i++) { + sum += Character.getNumericValue(values[i]) * GTIN_8_CHECK_DIGITS[i]; } + int checkDigit = 10 - sum % 10; + if (checkDigit == 10) { + return new String(ArrayUtils.add(values, Character.forDigit(0, 10))); + } else { + return new String(ArrayUtils.add(values, Character.forDigit(checkDigit, 10))); + } + } + + public String ean13() { + return gtin13(); + } - private static final int[] GTIN_8_CHECK_DIGITS = { 3, 1, 3, 1, 3, 1, 3 }; - private static final int[] GTIN_13_CHECK_DIGITS = { 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3 }; + public String gtin13() { + char[] values = faker.regexify("\\d{12}").toCharArray(); + int sum = 0; + for (int i = 0; i < values.length; i++) { + sum += Character.getNumericValue(values[i]) * GTIN_13_CHECK_DIGITS[i]; + } + int checkDigit = 10 - sum % 10; + if (checkDigit == 10) { + return new String(ArrayUtils.add(values, Character.forDigit(0, 10))); + } else { + return new String(ArrayUtils.add(values, Character.forDigit(checkDigit, 10))); + } + } + private static final int[] GTIN_8_CHECK_DIGITS = {3, 1, 3, 1, 3, 1, 3}; + private static final int[] GTIN_13_CHECK_DIGITS = {1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3}; } diff --git a/src/main/java/org/thejavaguy/javafaker/Coin.java b/src/main/java/org/thejavaguy/javafaker/Coin.java index d43fcbc..4fd7fed 100644 --- a/src/main/java/org/thejavaguy/javafaker/Coin.java +++ b/src/main/java/org/thejavaguy/javafaker/Coin.java @@ -2,16 +2,16 @@ public class Coin { - private final Faker faker; + private final Faker faker; - protected Coin(Faker faker) { - this.faker = faker; - } + protected Coin(Faker faker) { + this.faker = faker; + } - /** - * @return coin side e.g. "Heads", "Tails". - */ - public String flip() { - return faker.fakeValuesService().resolve("coin.flip", this, faker); - } + /** + * @return coin side e.g. "Heads", "Tails". + */ + public String flip() { + return faker.fakeValuesService().resolve("coin.flip", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Color.java b/src/main/java/org/thejavaguy/javafaker/Color.java index 6b03d7d..a3e08f8 100644 --- a/src/main/java/org/thejavaguy/javafaker/Color.java +++ b/src/main/java/org/thejavaguy/javafaker/Color.java @@ -1,24 +1,23 @@ package org.thejavaguy.javafaker; public class Color { - private final Faker faker; + private final Faker faker; - protected Color(Faker faker) { - this.faker = faker; - } + protected Color(Faker faker) { + this.faker = faker; + } - public String name() { - return faker.fakeValuesService().resolve("color.name", this, faker); - } + public String name() { + return faker.fakeValuesService().resolve("color.name", this, faker); + } - public String hex() { - return hex(true); - } + public String hex() { + return hex(true); + } - public String hex(boolean includeHashSign) { - String hexString = faker.random().hex(6); - if(includeHashSign) - return "#" + hexString; - return hexString; - } + public String hex(boolean includeHashSign) { + String hexString = faker.random().hex(6); + if (includeHashSign) return "#" + hexString; + return hexString; + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Commerce.java b/src/main/java/org/thejavaguy/javafaker/Commerce.java index f4bbaff..67bc16f 100644 --- a/src/main/java/org/thejavaguy/javafaker/Commerce.java +++ b/src/main/java/org/thejavaguy/javafaker/Commerce.java @@ -3,64 +3,65 @@ import java.text.DecimalFormat; import java.util.SortedSet; import java.util.TreeSet; - import org.apache.commons.lang3.StringUtils; public class Commerce { - private final Faker faker; + private final Faker faker; - protected Commerce(Faker faker) { - this.faker = faker; - } + protected Commerce(Faker faker) { + this.faker = faker; + } - public String color() { - return faker.fakeValuesService().resolve("color.name", this, faker); - } + public String color() { + return faker.fakeValuesService().resolve("color.name", this, faker); + } - public String department() { - int numberOfDepartments = Math.max(faker.random().nextInt(4), 1); - SortedSet departments = new TreeSet<>(); - while (departments.size() < numberOfDepartments) { - departments.add(faker.fakeValuesService().resolve("commerce.department", this, faker)); - } - if (departments.size() > 1) { - String lastDepartment = departments.last(); - return StringUtils.join(departments.headSet(lastDepartment), ", ") + " & " + lastDepartment; - } else { - return departments.first(); - } + public String department() { + int numberOfDepartments = Math.max(faker.random().nextInt(4), 1); + SortedSet departments = new TreeSet<>(); + while (departments.size() < numberOfDepartments) { + departments.add(faker.fakeValuesService().resolve("commerce.department", this, faker)); } - - public String productName() { - return StringUtils.join(new String[] { - faker.fakeValuesService().resolve("commerce.product_name.adjective", this,faker), - faker.fakeValuesService().resolve("commerce.product_name.material", this, faker), - faker.fakeValuesService().resolve("commerce.product_name.product", this, faker) }, " "); + if (departments.size() > 1) { + String lastDepartment = departments.last(); + return StringUtils.join(departments.headSet(lastDepartment), ", ") + " & " + lastDepartment; + } else { + return departments.first(); } + } - public String material() { - return faker.fakeValuesService().resolve("commerce.product_name.material", this, faker); - } + public String productName() { + return StringUtils.join( + new String[] { + faker.fakeValuesService().resolve("commerce.product_name.adjective", this, faker), + faker.fakeValuesService().resolve("commerce.product_name.material", this, faker), + faker.fakeValuesService().resolve("commerce.product_name.product", this, faker) + }, + " "); + } - /** - * Generate a random price between 0.00 and 100.00 - */ - public String price() { - return price(0, 100); - } + public String material() { + return faker.fakeValuesService().resolve("commerce.product_name.material", this, faker); + } - public String price(double min, double max) { - double price = min + (faker.random().nextDouble() * (max - min)); - return new DecimalFormat("#0.00").format(price); - } + /** Generate a random price between 0.00 and 100.00 */ + public String price() { + return price(0, 100); + } - public String promotionCode() { - return promotionCode(6); - } + public String price(double min, double max) { + double price = min + (faker.random().nextDouble() * (max - min)); + return new DecimalFormat("#0.00").format(price); + } - public String promotionCode(int digits) { - return StringUtils.join(faker.resolve("commerce.promotion_code.adjective"), - faker.resolve("commerce.promotion_code.noun"), - faker.number().digits(digits)); - } + public String promotionCode() { + return promotionCode(6); + } + + public String promotionCode(int digits) { + return StringUtils.join( + faker.resolve("commerce.promotion_code.adjective"), + faker.resolve("commerce.promotion_code.noun"), + faker.number().digits(digits)); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Company.java b/src/main/java/org/thejavaguy/javafaker/Company.java index 6c52e70..09d0db2 100644 --- a/src/main/java/org/thejavaguy/javafaker/Company.java +++ b/src/main/java/org/thejavaguy/javafaker/Company.java @@ -4,94 +4,84 @@ import java.util.ArrayList; import java.util.List; - import org.apache.commons.lang3.StringUtils; - import org.thejavaguy.javafaker.service.FakerIDN; public class Company { - private final Faker faker; - - protected Company(Faker faker) { - this.faker = faker; - } - - public String name() { - return faker.fakeValuesService().resolve("company.name", this, faker); - } - - public String suffix() { - return faker.fakeValuesService().resolve("company.suffix", this, faker); - } - - public String industry() { - return faker.fakeValuesService().resolve("company.industry", this, faker); - } - - public String profession() { - return faker.fakeValuesService().resolve("company.profession", this, faker); - } + private final Faker faker; - public String buzzword() { - @SuppressWarnings("unchecked") - List> buzzwordLists = (List>) faker.fakeValuesService().fetchObject("company.buzzwords"); - List buzzwords = new ArrayList<>(); - for (List buzzwordList : buzzwordLists) { - buzzwords.addAll(buzzwordList); - } - return buzzwords.get(faker.random().nextInt(buzzwords.size())); - } - - /** - * Generate a buzzword-laden catch phrase. - */ - public String catchPhrase() { - @SuppressWarnings("unchecked") - List> catchPhraseLists = (List>) faker.fakeValuesService().fetchObject("company.buzzwords"); - return joinSampleOfEachList(catchPhraseLists, " "); - } + protected Company(Faker faker) { + this.faker = faker; + } - /** - * When a straight answer won't do, BS to the rescue! - */ - public String bs() { - @SuppressWarnings("unchecked") - List> buzzwordLists = (List>) faker.fakeValuesService().fetchObject("company.bs"); - return joinSampleOfEachList(buzzwordLists, " "); - } + public String name() { + return faker.fakeValuesService().resolve("company.name", this, faker); + } - /** - * Generate a random company logo url in PNG format. - */ - public String logo() { - int number = faker.random().nextInt(13) + 1; - return "https://pigment.github.io/fake-logos/logos/medium/color/" + number + ".png"; - } + public String suffix() { + return faker.fakeValuesService().resolve("company.suffix", this, faker); + } - public String url() { - return join( - "www", - ".", - FakerIDN.toASCII(domainName()), - ".", - domainSuffix() - ); - } + public String industry() { + return faker.fakeValuesService().resolve("company.industry", this, faker); + } - private String domainName(){ - return StringUtils.deleteWhitespace(name().toLowerCase().replaceAll(",", "").replaceAll("'", "")); - } + public String profession() { + return faker.fakeValuesService().resolve("company.profession", this, faker); + } - private String domainSuffix() { - return faker.fakeValuesService().resolve("internet.domain_suffix", this, faker); + public String buzzword() { + @SuppressWarnings("unchecked") + List> buzzwordLists = + (List>) faker.fakeValuesService().fetchObject("company.buzzwords"); + List buzzwords = new ArrayList<>(); + for (List buzzwordList : buzzwordLists) { + buzzwords.addAll(buzzwordList); } - - private String joinSampleOfEachList(List> listOfLists, String separator) { - List words = new ArrayList<>(); - for (List list : listOfLists) { - words.add(list.get(faker.random().nextInt(list.size()))); - } - return join(words, separator); + return buzzwords.get(faker.random().nextInt(buzzwords.size())); + } + + /** Generate a buzzword-laden catch phrase. */ + public String catchPhrase() { + @SuppressWarnings("unchecked") + List> catchPhraseLists = + (List>) faker.fakeValuesService().fetchObject("company.buzzwords"); + return joinSampleOfEachList(catchPhraseLists, " "); + } + + /** When a straight answer won't do, BS to the rescue! */ + public String bs() { + @SuppressWarnings("unchecked") + List> buzzwordLists = + (List>) faker.fakeValuesService().fetchObject("company.bs"); + return joinSampleOfEachList(buzzwordLists, " "); + } + + /** Generate a random company logo url in PNG format. */ + public String logo() { + int number = faker.random().nextInt(13) + 1; + return "https://pigment.github.io/fake-logos/logos/medium/color/" + number + ".png"; + } + + public String url() { + return join("www", ".", FakerIDN.toASCII(domainName()), ".", domainSuffix()); + } + + private String domainName() { + return StringUtils.deleteWhitespace( + name().toLowerCase().replaceAll(",", "").replaceAll("'", "")); + } + + private String domainSuffix() { + return faker.fakeValuesService().resolve("internet.domain_suffix", this, faker); + } + + private String joinSampleOfEachList(List> listOfLists, String separator) { + List words = new ArrayList<>(); + for (List list : listOfLists) { + words.add(list.get(faker.random().nextInt(list.size()))); } + return join(words, separator); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Country.java b/src/main/java/org/thejavaguy/javafaker/Country.java index 27ba7fc..08d8f2b 100644 --- a/src/main/java/org/thejavaguy/javafaker/Country.java +++ b/src/main/java/org/thejavaguy/javafaker/Country.java @@ -1,40 +1,39 @@ package org.thejavaguy.javafaker; public class Country { - private final Faker faker; - private final String flagUrl; + private final Faker faker; + private final String flagUrl; - protected Country(Faker faker) { - this.faker = faker; - this.flagUrl = "http://flags.fmcdn.net/data/flags/w580/"; - } + protected Country(Faker faker) { + this.faker = faker; + this.flagUrl = "http://flags.fmcdn.net/data/flags/w580/"; + } - public String flag() { - return flagUrl + faker.fakeValuesService().resolve("country.code2", this, faker) + ".png"; - } + public String flag() { + return flagUrl + faker.fakeValuesService().resolve("country.code2", this, faker) + ".png"; + } - public String countryCode2() { - return faker.fakeValuesService().resolve("country.code2", this, faker); - } + public String countryCode2() { + return faker.fakeValuesService().resolve("country.code2", this, faker); + } - public String countryCode3() { - return faker.fakeValuesService().resolve("country.code3", this, faker); - } + public String countryCode3() { + return faker.fakeValuesService().resolve("country.code3", this, faker); + } - public String capital() { - return faker.fakeValuesService().resolve("country.capital", this, faker); - } + public String capital() { + return faker.fakeValuesService().resolve("country.capital", this, faker); + } - public String currency() { - return faker.fakeValuesService().resolve("country.currency", this, faker); - } + public String currency() { + return faker.fakeValuesService().resolve("country.currency", this, faker); + } - public String currencyCode() { - return faker.fakeValuesService().resolve("country.currency_code", this, faker); - } - - public String name() { - return faker.fakeValuesService().resolve("country.name", this, faker); - } + public String currencyCode() { + return faker.fakeValuesService().resolve("country.currency_code", this, faker); + } + public String name() { + return faker.fakeValuesService().resolve("country.name", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/CreditCard.java b/src/main/java/org/thejavaguy/javafaker/CreditCard.java index caf33aa..c9912e5 100644 --- a/src/main/java/org/thejavaguy/javafaker/CreditCard.java +++ b/src/main/java/org/thejavaguy/javafaker/CreditCard.java @@ -5,220 +5,230 @@ import java.time.format.DateTimeFormatter; /** - * Generates realistic credit card fake data including numbers, - * expiration dates, CVVs, and cardholder information. + * Generates realistic credit card fake data including numbers, expiration dates, CVVs, and + * cardholder information. * - *

All generated card numbers pass Luhn validation but are not - * real card numbers and should only be used for testing purposes.

+ *

All generated card numbers pass Luhn validation but are not real card numbers and should only + * be used for testing purposes. * * @since 1.x.x */ public class CreditCard { - private final Faker faker; - - protected CreditCard(Faker faker) { - this.faker = faker; - } - - /** - * Generates a random credit card number from any supported type. - * The number includes a valid Luhn check digit. - * - * @return a valid credit card number string with dashes - */ - public String number() { - CreditCardType type = randomType(); - return number(type); - } - - /** - * Generates a credit card number for the specified type. - * The number includes a valid Luhn check digit. - * - * @param type the credit card type - * @return a valid credit card number string with dashes - */ - public String number(CreditCardType type) { - // Delegate to Finance for Luhn calculation - return faker.finance().creditCard(type); - } - - /** - * Generates a credit card number without dashes or spaces. - * - * @return a plain credit card number string - */ - public String numberPlain() { - return number().replaceAll("[\\s-]", ""); - } - - /** - * Generates a credit card number without dashes for the specified type. - * - * @param type the credit card type - * @return a plain credit card number string - */ - public String numberPlain(CreditCardType type) { - return number(type).replaceAll("[\\s-]", ""); - } - - /** - * Returns a random credit card type. - * - * @return a {@link CreditCardType} value - */ - public CreditCardType type() { - return randomType(); - } - - /** - * Generates a CVV/CVC security code. - * Returns 4 digits for American Express, 3 digits for all other types. - * - * @return a CVV string, e.g., "123" or "1234" - */ - public String cvv() { - return faker.numerify("###"); - } - - /** - * Generates a CVV/CVC for the specified card type. - * American Express uses 4 digits; others use 3. - * - * @param type the credit card type - * @return a CVV string appropriate for the card type - */ - public String cvv(CreditCardType type) { - if (type == CreditCardType.AMERICAN_EXPRESS) { - return faker.numerify("####"); - } - return faker.numerify("###"); - } - - /** - * Generates a valid expiration date in MM/YY format. - * The date will be between 1 month and 5 years in the future. - * - * @return expiration date string, e.g., "03/27" - */ - public String expirationDate() { - return expirationDate("MM/yy"); - } - - /** - * Generates a valid expiration date in the specified format. - * - * @param pattern the date format pattern (e.g., "MM/yy", "MM/yyyy") - * @return formatted expiration date string - */ - public String expirationDate(String pattern) { - LocalDate now = LocalDate.now(); - // Random months from 1 to 60 (5 years) in the future - int monthsAhead = faker.random().nextInt(59) + 1; - YearMonth expiry = YearMonth.from(now).plusMonths(monthsAhead); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); - return expiry.format(formatter); - } - - /** - * Generates an expired card date (in the past). - * - * @return expiration date string in MM/YY format - */ - public String expiredDate() { - LocalDate now = LocalDate.now(); - // Random months from 1 to 36 (3 years) in the past - int monthsBack = faker.random().nextInt(35) + 1; - YearMonth expiry = YearMonth.from(now).minusMonths(monthsBack); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/yy"); - return expiry.format(formatter); - } - - /** - * Generates a cardholder name using the Name faker. - * - * @return full name in uppercase, e.g., "JOHN SMITH" - */ - public String cardholderName() { - return (faker.name().firstName() + " " + faker.name().lastName()).toUpperCase(); - } - - /** - * Returns a random issuing bank name. - * - * @return bank name, e.g., "Chase", "Capital One" - */ - public String bank() { - return faker.fakeValuesService().fetchString("credit_card.banks"); - } - - /** - * Generates the last 4 digits of a card number. - * Useful for display/masking scenarios. - * - * @return 4 random digits, e.g., "4532" - */ - public String lastFourDigits() { - return faker.numerify("####"); - } - - /** - * Generates a masked card number showing only last 4 digits. - * - * @return masked number, e.g., "**** **** **** 4532" - */ - public String maskedNumber() { - return "**** **** **** " + lastFourDigits(); - } - - /** - * Generates a masked card number for the specified type. - * - * @param type the credit card type - * @return masked number with proper format for the type - */ - public String maskedNumber(CreditCardType type) { - if (type == CreditCardType.AMERICAN_EXPRESS) { - return "**** ****** *" + faker.numerify("####"); - } - return maskedNumber(); - } - - /** - * Returns the card network name for a given type. - * - * @param type the credit card type - * @return network name, e.g., "Visa", "Mastercard" - */ - public String network(CreditCardType type) { - switch (type) { - case VISA: return "Visa"; - case MASTERCARD: return "Mastercard"; - case AMERICAN_EXPRESS: return "American Express"; - case DISCOVER: return "Discover"; - case DINERS_CLUB: return "Diners Club"; - case JCB: return "JCB"; - case SWITCH: return "Switch"; - case SOLO: return "Solo"; - case DANKORT: return "Dankort"; - case FORBRUGSFORENINGEN: return "Forbrugsforeningen"; - case LASER: return "Laser"; - default: return type.name(); - } - } - - /** - * Returns the card network name for a randomly selected type. - * - * @return network name - */ - public String network() { - return network(randomType()); - } - - private CreditCardType randomType() { - CreditCardType[] types = CreditCardType.values(); - return types[faker.random().nextInt(types.length)]; - } + private final Faker faker; + + protected CreditCard(Faker faker) { + this.faker = faker; + } + + /** + * Generates a random credit card number from any supported type. The number includes a valid Luhn + * check digit. + * + * @return a valid credit card number string with dashes + */ + public String number() { + CreditCardType type = randomType(); + return number(type); + } + + /** + * Generates a credit card number for the specified type. The number includes a valid Luhn check + * digit. + * + * @param type the credit card type + * @return a valid credit card number string with dashes + */ + public String number(CreditCardType type) { + // Delegate to Finance for Luhn calculation + return faker.finance().creditCard(type); + } + + /** + * Generates a credit card number without dashes or spaces. + * + * @return a plain credit card number string + */ + public String numberPlain() { + return number().replaceAll("[\\s-]", ""); + } + + /** + * Generates a credit card number without dashes for the specified type. + * + * @param type the credit card type + * @return a plain credit card number string + */ + public String numberPlain(CreditCardType type) { + return number(type).replaceAll("[\\s-]", ""); + } + + /** + * Returns a random credit card type. + * + * @return a {@link CreditCardType} value + */ + public CreditCardType type() { + return randomType(); + } + + /** + * Generates a CVV/CVC security code. Returns 4 digits for American Express, 3 digits for all + * other types. + * + * @return a CVV string, e.g., "123" or "1234" + */ + public String cvv() { + return faker.numerify("###"); + } + + /** + * Generates a CVV/CVC for the specified card type. American Express uses 4 digits; others use 3. + * + * @param type the credit card type + * @return a CVV string appropriate for the card type + */ + public String cvv(CreditCardType type) { + if (type == CreditCardType.AMERICAN_EXPRESS) { + return faker.numerify("####"); + } + return faker.numerify("###"); + } + + /** + * Generates a valid expiration date in MM/YY format. The date will be between 1 month and 5 years + * in the future. + * + * @return expiration date string, e.g., "03/27" + */ + public String expirationDate() { + return expirationDate("MM/yy"); + } + + /** + * Generates a valid expiration date in the specified format. + * + * @param pattern the date format pattern (e.g., "MM/yy", "MM/yyyy") + * @return formatted expiration date string + */ + public String expirationDate(String pattern) { + LocalDate now = LocalDate.now(); + // Random months from 1 to 60 (5 years) in the future + int monthsAhead = faker.random().nextInt(59) + 1; + YearMonth expiry = YearMonth.from(now).plusMonths(monthsAhead); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); + return expiry.format(formatter); + } + + /** + * Generates an expired card date (in the past). + * + * @return expiration date string in MM/YY format + */ + public String expiredDate() { + LocalDate now = LocalDate.now(); + // Random months from 1 to 36 (3 years) in the past + int monthsBack = faker.random().nextInt(35) + 1; + YearMonth expiry = YearMonth.from(now).minusMonths(monthsBack); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/yy"); + return expiry.format(formatter); + } + + /** + * Generates a cardholder name using the Name faker. + * + * @return full name in uppercase, e.g., "JOHN SMITH" + */ + public String cardholderName() { + return (faker.name().firstName() + " " + faker.name().lastName()).toUpperCase(); + } + + /** + * Returns a random issuing bank name. + * + * @return bank name, e.g., "Chase", "Capital One" + */ + public String bank() { + return faker.fakeValuesService().fetchString("credit_card.banks"); + } + + /** + * Generates the last 4 digits of a card number. Useful for display/masking scenarios. + * + * @return 4 random digits, e.g., "4532" + */ + public String lastFourDigits() { + return faker.numerify("####"); + } + + /** + * Generates a masked card number showing only last 4 digits. + * + * @return masked number, e.g., "**** **** **** 4532" + */ + public String maskedNumber() { + return "**** **** **** " + lastFourDigits(); + } + + /** + * Generates a masked card number for the specified type. + * + * @param type the credit card type + * @return masked number with proper format for the type + */ + public String maskedNumber(CreditCardType type) { + if (type == CreditCardType.AMERICAN_EXPRESS) { + return "**** ****** *" + faker.numerify("####"); + } + return maskedNumber(); + } + + /** + * Returns the card network name for a given type. + * + * @param type the credit card type + * @return network name, e.g., "Visa", "Mastercard" + */ + public String network(CreditCardType type) { + switch (type) { + case VISA: + return "Visa"; + case MASTERCARD: + return "Mastercard"; + case AMERICAN_EXPRESS: + return "American Express"; + case DISCOVER: + return "Discover"; + case DINERS_CLUB: + return "Diners Club"; + case JCB: + return "JCB"; + case SWITCH: + return "Switch"; + case SOLO: + return "Solo"; + case DANKORT: + return "Dankort"; + case FORBRUGSFORENINGEN: + return "Forbrugsforeningen"; + case LASER: + return "Laser"; + default: + return type.name(); + } + } + + /** + * Returns the card network name for a randomly selected type. + * + * @return network name + */ + public String network() { + return network(randomType()); + } + + private CreditCardType randomType() { + CreditCardType[] types = CreditCardType.values(); + return types[faker.random().nextInt(types.length)]; + } } diff --git a/src/main/java/org/thejavaguy/javafaker/CreditCardType.java b/src/main/java/org/thejavaguy/javafaker/CreditCardType.java index bab156e..1c368ff 100644 --- a/src/main/java/org/thejavaguy/javafaker/CreditCardType.java +++ b/src/main/java/org/thejavaguy/javafaker/CreditCardType.java @@ -1,15 +1,15 @@ package org.thejavaguy.javafaker; public enum CreditCardType { - VISA, - MASTERCARD, - DISCOVER, - AMERICAN_EXPRESS, - DINERS_CLUB, - JCB, - SWITCH, - SOLO, - DANKORT, - FORBRUGSFORENINGEN, - LASER + VISA, + MASTERCARD, + DISCOVER, + AMERICAN_EXPRESS, + DINERS_CLUB, + JCB, + SWITCH, + SOLO, + DANKORT, + FORBRUGSFORENINGEN, + LASER } diff --git a/src/main/java/org/thejavaguy/javafaker/Crypto.java b/src/main/java/org/thejavaguy/javafaker/Crypto.java index ddd8c7b..43daf7f 100644 --- a/src/main/java/org/thejavaguy/javafaker/Crypto.java +++ b/src/main/java/org/thejavaguy/javafaker/Crypto.java @@ -5,37 +5,36 @@ import java.security.NoSuchAlgorithmException; public class Crypto { - private final Faker faker; - - protected Crypto(Faker faker) { - this.faker = faker; - } - - public String md5() { - return generateString("MD5"); - } - - public String sha1() { - return generateString("SHA-1"); - } - - public String sha256() { - return generateString("SHA-256"); - } - - public String sha512() { - return generateString("SHA-512"); + private final Faker faker; + + protected Crypto(Faker faker) { + this.faker = faker; + } + + public String md5() { + return generateString("MD5"); + } + + public String sha1() { + return generateString("SHA-1"); + } + + public String sha256() { + return generateString("SHA-256"); + } + + public String sha512() { + return generateString("SHA-512"); + } + + private String generateString(String algorithm) { + try { + MessageDigest messageDigest = MessageDigest.getInstance(algorithm); + String characters = faker.lorem().characters(); + messageDigest.update(characters.getBytes(), 0, characters.length()); + return new BigInteger(1, messageDigest.digest()).toString(16); + } catch (NoSuchAlgorithmException noSuchAlgorithmException) { + throw new RuntimeException(noSuchAlgorithmException); } - - private String generateString(String algorithm) { - try { - MessageDigest messageDigest = MessageDigest.getInstance(algorithm); - String characters = faker.lorem().characters(); - messageDigest.update(characters.getBytes(), 0, characters.length()); - return new BigInteger(1, messageDigest.digest()).toString(16); - } catch (NoSuchAlgorithmException noSuchAlgorithmException) { - throw new RuntimeException(noSuchAlgorithmException); - } - } - + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Currency.java b/src/main/java/org/thejavaguy/javafaker/Currency.java index 66e8749..16792d0 100644 --- a/src/main/java/org/thejavaguy/javafaker/Currency.java +++ b/src/main/java/org/thejavaguy/javafaker/Currency.java @@ -2,17 +2,17 @@ public class Currency { - private final Faker faker; + private final Faker faker; - public Currency(Faker faker) { - this.faker = faker; - } + public Currency(Faker faker) { + this.faker = faker; + } - public String name() { - return faker.fakeValuesService().resolve("currency.name", this, faker); - } + public String name() { + return faker.fakeValuesService().resolve("currency.name", this, faker); + } - public String code() { - return faker.fakeValuesService().resolve("currency.code", this, faker); - } + public String code() { + return faker.fakeValuesService().resolve("currency.code", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/DateAndTime.java b/src/main/java/org/thejavaguy/javafaker/DateAndTime.java index a733428..2d684e0 100644 --- a/src/main/java/org/thejavaguy/javafaker/DateAndTime.java +++ b/src/main/java/org/thejavaguy/javafaker/DateAndTime.java @@ -1,6 +1,4 @@ -/** - * - */ +/** */ package org.thejavaguy.javafaker; import java.util.Calendar; @@ -12,174 +10,153 @@ * A generator of random dates. * * @author pmiklos - * */ public class DateAndTime { - private static final int DEFAULT_MIN_AGE = 18; - private static final int DEFAULT_MAX_AGE = 65; - - private final Faker faker; - - protected DateAndTime(Faker faker) { - this.faker = faker; - } - - /** - * Generates a future date from now. Note that there is a 1 second slack to avoid generating a past date. - * - * @param atMost - * at most this amount of time ahead from now exclusive. - * @param unit - * the time unit. - * @return a future date from now. - */ - public Date future(int atMost, TimeUnit unit) { - Date now = new Date(); - Date aBitLaterThanNow = new Date(now.getTime() + 1000); - return future(atMost, unit, aBitLaterThanNow); - } - - /** - * Generates a future date from now, with a minimum time. - * - * @param atMost - * at most this amount of time ahead from now exclusive. - * @param minimum - * the minimum amount of time in the future from now. - * @param unit - * the time unit. - * @return a future date from now. - */ - public Date future(int atMost, int minimum, TimeUnit unit) { - Date now = new Date(); - Date minimumDate = new Date(now.getTime() + unit.toMillis(minimum)); - return future(atMost - minimum, unit, minimumDate); - } - - /** - * Generates a future date relative to the {@code referenceDate}. - * - * @param atMost - * at most this amount of time ahead to the {@code referenceDate} exclusive. - * @param unit - * the time unit. - * @param referenceDate - * the future date relative to this date. - * @return a future date relative to {@code referenceDate}. - */ - public Date future(int atMost, TimeUnit unit, Date referenceDate) { - long upperBound = unit.toMillis(atMost); - - long futureMillis = referenceDate.getTime(); - futureMillis += 1 + faker.random().nextLong(upperBound - 1); - - return new Date(futureMillis); - } - - /** - * Generates a past date from now. Note that there is a 1 second slack added. - * - * @param atMost - * at most this amount of time earlier from now exclusive. - * @param unit - * the time unit. - * @return a past date from now. - */ - public Date past(int atMost, TimeUnit unit) { - Date now = new Date(); - Date aBitEarlierThanNow = new Date(now.getTime() - 1000); - return past(atMost, unit, aBitEarlierThanNow); - } - - /** - * Generates a past date from now, with a minimum time. - * - * @param atMost - * at most this amount of time earlier from now exclusive. - * @param minimum - * the minimum amount of time in the past from now. - * @param unit - * the time unit. - * @return a past date from now. - */ - public Date past(int atMost, int minimum, TimeUnit unit) { - Date now = new Date(); - Date minimumDate = new Date(now.getTime() - unit.toMillis(minimum)); - return past(atMost - minimum, unit, minimumDate); - } - - /** - * Generates a past date relative to the {@code referenceDate}. - * - * @param atMost - * at most this amount of time past to the {@code referenceDate} exclusive. - * @param unit - * the time unit. - * @param referenceDate - * the past date relative to this date. - * @return a past date relative to {@code referenceDate}. - */ - public Date past(int atMost, TimeUnit unit, Date referenceDate) { - long upperBound = unit.toMillis(atMost); - - long futureMillis = referenceDate.getTime(); - futureMillis -= 1 + faker.random().nextLong(upperBound - 1); - - return new Date(futureMillis); - } - - /** - * Generates a random date between two dates. - * - * @param from - * the lower bound inclusive - * @param to - * the upper bound exclusive - * @return a random date between {@code from} and {@code to}. - * @throws IllegalArgumentException - * if the {@code to} date represents an earlier date than {@code from} date. - */ - public Date between(Date from, Date to) throws IllegalArgumentException { - if (to.before(from)) { - throw new IllegalArgumentException("Invalid date range, the upper bound date is before the lower bound."); - } - - if (from.equals(to)) { - return from; - } - - long offsetMillis = faker.random().nextLong(to.getTime() - from.getTime()); - return new Date(from.getTime() + offsetMillis); - } - - /** - * Generates a random birthday between 65 and 18 years ago from now. - * - * @return a random birthday between 65 and 18 years ago from now. - */ - public Date birthday() { - return birthday(DEFAULT_MIN_AGE, DEFAULT_MAX_AGE); + private static final int DEFAULT_MIN_AGE = 18; + private static final int DEFAULT_MAX_AGE = 65; + + private final Faker faker; + + protected DateAndTime(Faker faker) { + this.faker = faker; + } + + /** + * Generates a future date from now. Note that there is a 1 second slack to avoid generating a + * past date. + * + * @param atMost at most this amount of time ahead from now exclusive. + * @param unit the time unit. + * @return a future date from now. + */ + public Date future(int atMost, TimeUnit unit) { + Date now = new Date(); + Date aBitLaterThanNow = new Date(now.getTime() + 1000); + return future(atMost, unit, aBitLaterThanNow); + } + + /** + * Generates a future date from now, with a minimum time. + * + * @param atMost at most this amount of time ahead from now exclusive. + * @param minimum the minimum amount of time in the future from now. + * @param unit the time unit. + * @return a future date from now. + */ + public Date future(int atMost, int minimum, TimeUnit unit) { + Date now = new Date(); + Date minimumDate = new Date(now.getTime() + unit.toMillis(minimum)); + return future(atMost - minimum, unit, minimumDate); + } + + /** + * Generates a future date relative to the {@code referenceDate}. + * + * @param atMost at most this amount of time ahead to the {@code referenceDate} exclusive. + * @param unit the time unit. + * @param referenceDate the future date relative to this date. + * @return a future date relative to {@code referenceDate}. + */ + public Date future(int atMost, TimeUnit unit, Date referenceDate) { + long upperBound = unit.toMillis(atMost); + + long futureMillis = referenceDate.getTime(); + futureMillis += 1 + faker.random().nextLong(upperBound - 1); + + return new Date(futureMillis); + } + + /** + * Generates a past date from now. Note that there is a 1 second slack added. + * + * @param atMost at most this amount of time earlier from now exclusive. + * @param unit the time unit. + * @return a past date from now. + */ + public Date past(int atMost, TimeUnit unit) { + Date now = new Date(); + Date aBitEarlierThanNow = new Date(now.getTime() - 1000); + return past(atMost, unit, aBitEarlierThanNow); + } + + /** + * Generates a past date from now, with a minimum time. + * + * @param atMost at most this amount of time earlier from now exclusive. + * @param minimum the minimum amount of time in the past from now. + * @param unit the time unit. + * @return a past date from now. + */ + public Date past(int atMost, int minimum, TimeUnit unit) { + Date now = new Date(); + Date minimumDate = new Date(now.getTime() - unit.toMillis(minimum)); + return past(atMost - minimum, unit, minimumDate); + } + + /** + * Generates a past date relative to the {@code referenceDate}. + * + * @param atMost at most this amount of time past to the {@code referenceDate} exclusive. + * @param unit the time unit. + * @param referenceDate the past date relative to this date. + * @return a past date relative to {@code referenceDate}. + */ + public Date past(int atMost, TimeUnit unit, Date referenceDate) { + long upperBound = unit.toMillis(atMost); + + long futureMillis = referenceDate.getTime(); + futureMillis -= 1 + faker.random().nextLong(upperBound - 1); + + return new Date(futureMillis); + } + + /** + * Generates a random date between two dates. + * + * @param from the lower bound inclusive + * @param to the upper bound exclusive + * @return a random date between {@code from} and {@code to}. + * @throws IllegalArgumentException if the {@code to} date represents an earlier date than {@code + * from} date. + */ + public Date between(Date from, Date to) throws IllegalArgumentException { + if (to.before(from)) { + throw new IllegalArgumentException( + "Invalid date range, the upper bound date is before the lower bound."); } - /** - * Generates a random birthday between two ages from now. - * - * @param minAge - * the minimal age - * @param maxAge - * the maximal age - * @return a random birthday between {@code minAge} and {@code maxAge} years ago from now. - * @throws IllegalArgumentException - * if the {@code maxAge} is lower than {@code minAge}. - */ - public Date birthday(int minAge, int maxAge) { - int currentYear = Calendar.getInstance().get(Calendar.YEAR); - int currentMonth = Calendar.getInstance().get(Calendar.MONTH); - int currentDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); - Calendar from = new GregorianCalendar(currentYear - maxAge, currentMonth, currentDay); - Calendar to = new GregorianCalendar(currentYear - minAge, currentMonth, currentDay); - - return between(from.getTime(), to.getTime()); + if (from.equals(to)) { + return from; } + long offsetMillis = faker.random().nextLong(to.getTime() - from.getTime()); + return new Date(from.getTime() + offsetMillis); + } + + /** + * Generates a random birthday between 65 and 18 years ago from now. + * + * @return a random birthday between 65 and 18 years ago from now. + */ + public Date birthday() { + return birthday(DEFAULT_MIN_AGE, DEFAULT_MAX_AGE); + } + + /** + * Generates a random birthday between two ages from now. + * + * @param minAge the minimal age + * @param maxAge the maximal age + * @return a random birthday between {@code minAge} and {@code maxAge} years ago from now. + * @throws IllegalArgumentException if the {@code maxAge} is lower than {@code minAge}. + */ + public Date birthday(int minAge, int maxAge) { + int currentYear = Calendar.getInstance().get(Calendar.YEAR); + int currentMonth = Calendar.getInstance().get(Calendar.MONTH); + int currentDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); + Calendar from = new GregorianCalendar(currentYear - maxAge, currentMonth, currentDay); + Calendar to = new GregorianCalendar(currentYear - minAge, currentMonth, currentDay); + + return between(from.getTime(), to.getTime()); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Demographic.java b/src/main/java/org/thejavaguy/javafaker/Demographic.java index 67015fd..0cec65c 100644 --- a/src/main/java/org/thejavaguy/javafaker/Demographic.java +++ b/src/main/java/org/thejavaguy/javafaker/Demographic.java @@ -2,29 +2,29 @@ public class Demographic { - private final Faker faker; + private final Faker faker; - protected Demographic(Faker faker) { - this.faker = faker; - } + protected Demographic(Faker faker) { + this.faker = faker; + } - public String race() { - return faker.fakeValuesService().fetchString("demographic.race"); - } + public String race() { + return faker.fakeValuesService().fetchString("demographic.race"); + } - public String educationalAttainment() { - return faker.fakeValuesService().fetchString("demographic.educational_attainment"); - } + public String educationalAttainment() { + return faker.fakeValuesService().fetchString("demographic.educational_attainment"); + } - public String demonym() { - return faker.fakeValuesService().fetchString("demographic.demonym"); - } + public String demonym() { + return faker.fakeValuesService().fetchString("demographic.demonym"); + } - public String sex() { - return faker.fakeValuesService().fetchString("demographic.sex"); - } + public String sex() { + return faker.fakeValuesService().fetchString("demographic.sex"); + } - public String maritalStatus() { - return faker.fakeValuesService().fetchString("demographic.marital_status"); - } + public String maritalStatus() { + return faker.fakeValuesService().fetchString("demographic.marital_status"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Disease.java b/src/main/java/org/thejavaguy/javafaker/Disease.java index bf96792..5500aa4 100644 --- a/src/main/java/org/thejavaguy/javafaker/Disease.java +++ b/src/main/java/org/thejavaguy/javafaker/Disease.java @@ -1,73 +1,81 @@ package org.thejavaguy.javafaker; -/** - * Generate random, different kinds of disease. - */ +/** Generate random, different kinds of disease. */ public class Disease { - private final Faker faker; + private final Faker faker; - /** - * Create a constructor for Disease - * @param faker The Faker instance for generating random, different kinds of disease, e.g. the internal disease. - */ - protected Disease(Faker faker) { - this.faker = faker; - } + /** + * Create a constructor for Disease + * + * @param faker The Faker instance for generating random, different kinds of disease, e.g. the + * internal disease. + */ + protected Disease(Faker faker) { + this.faker = faker; + } - /** - * Generate random internal disease - * @return An internal disease - */ - public String internalDisease() { - return faker.fakeValuesService().resolve("disease.internal_disease", this, faker); - } + /** + * Generate random internal disease + * + * @return An internal disease + */ + public String internalDisease() { + return faker.fakeValuesService().resolve("disease.internal_disease", this, faker); + } - /** - * Generate random neurology disease - * @return A neurology disease - */ - public String neurology() { - return faker.fakeValuesService().resolve("disease.neurology", this, faker); - } + /** + * Generate random neurology disease + * + * @return A neurology disease + */ + public String neurology() { + return faker.fakeValuesService().resolve("disease.neurology", this, faker); + } - /** - * Generate random surgery disease - * @return A surgery disease - */ - public String surgery() { - return faker.fakeValuesService().resolve("disease.surgery", this, faker); - } + /** + * Generate random surgery disease + * + * @return A surgery disease + */ + public String surgery() { + return faker.fakeValuesService().resolve("disease.surgery", this, faker); + } - /** - * Generate random paediatrics disease - * @return A paediatrics disease - */ - public String paediatrics() { - return faker.fakeValuesService().resolve("disease.paediatrics", this, faker); - } + /** + * Generate random paediatrics disease + * + * @return A paediatrics disease + */ + public String paediatrics() { + return faker.fakeValuesService().resolve("disease.paediatrics", this, faker); + } - /** - * Generate random gynecology and obstetrics disease - * @return A gynecology and obstetrics disease - */ - public String gynecologyAndObstetrics() { - return faker.fakeValuesService().resolve("disease.gynecology_and_obstetrics", this, faker); - } + /** + * Generate random gynecology and obstetrics disease + * + * @return A gynecology and obstetrics disease + */ + public String gynecologyAndObstetrics() { + return faker.fakeValuesService().resolve("disease.gynecology_and_obstetrics", this, faker); + } - /** - * Generate random ophthalmology and otorhinolaryngology disease - * @return A ophthalmology and otorhinolaryngology disease - */ - public String ophthalmologyAndOtorhinolaryngology() { - return faker.fakeValuesService().resolve("disease.ophthalmology_and_otorhinolaryngology", this, faker); - } - - /** - * Generate random dermatolory disease - * @return A dermatolory disease - */ - public String dermatolory() { - return faker.fakeValuesService().resolve("disease.dermatolory", this, faker); - } + /** + * Generate random ophthalmology and otorhinolaryngology disease + * + * @return A ophthalmology and otorhinolaryngology disease + */ + public String ophthalmologyAndOtorhinolaryngology() { + return faker + .fakeValuesService() + .resolve("disease.ophthalmology_and_otorhinolaryngology", this, faker); + } + /** + * Generate random dermatolory disease + * + * @return A dermatolory disease + */ + public String dermatolory() { + return faker.fakeValuesService().resolve("disease.dermatolory", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Dog.java b/src/main/java/org/thejavaguy/javafaker/Dog.java index dc8bf48..bea60c3 100644 --- a/src/main/java/org/thejavaguy/javafaker/Dog.java +++ b/src/main/java/org/thejavaguy/javafaker/Dog.java @@ -2,41 +2,41 @@ public class Dog { - private final Faker faker; + private final Faker faker; - protected Dog(Faker faker) { - this.faker = faker; - } + protected Dog(Faker faker) { + this.faker = faker; + } - public String name() { - return faker.fakeValuesService().resolve("creature.dog.name", this, faker); - } + public String name() { + return faker.fakeValuesService().resolve("creature.dog.name", this, faker); + } - public String breed() { - return faker.fakeValuesService().resolve("creature.dog.breed", this, faker); - } + public String breed() { + return faker.fakeValuesService().resolve("creature.dog.breed", this, faker); + } - public String sound() { - return faker.fakeValuesService().resolve("creature.dog.sound", this, faker); - } + public String sound() { + return faker.fakeValuesService().resolve("creature.dog.sound", this, faker); + } - public String memePhrase() { - return faker.fakeValuesService().resolve("creature.dog.meme_phrase", this, faker); - } + public String memePhrase() { + return faker.fakeValuesService().resolve("creature.dog.meme_phrase", this, faker); + } - public String age() { - return faker.fakeValuesService().resolve("creature.dog.age", this, faker); - } + public String age() { + return faker.fakeValuesService().resolve("creature.dog.age", this, faker); + } - public String coatLength() { - return faker.fakeValuesService().resolve("creature.dog.coat_length", this, faker); - } + public String coatLength() { + return faker.fakeValuesService().resolve("creature.dog.coat_length", this, faker); + } - public String gender() { - return faker.fakeValuesService().resolve("creature.dog.gender", this, faker); - } + public String gender() { + return faker.fakeValuesService().resolve("creature.dog.gender", this, faker); + } - public String size() { - return faker.fakeValuesService().resolve("creature.dog.size", this, faker); - } + public String size() { + return faker.fakeValuesService().resolve("creature.dog.size", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/DragonBall.java b/src/main/java/org/thejavaguy/javafaker/DragonBall.java index d28ec53..ea53735 100644 --- a/src/main/java/org/thejavaguy/javafaker/DragonBall.java +++ b/src/main/java/org/thejavaguy/javafaker/DragonBall.java @@ -1,13 +1,13 @@ package org.thejavaguy.javafaker; public class DragonBall { - private final Faker faker; + private final Faker faker; - protected DragonBall(Faker faker) { - this.faker = faker; - } + protected DragonBall(Faker faker) { + this.faker = faker; + } - public String character() { - return faker.fakeValuesService().resolve("dragon_ball.characters", this, faker); - } + public String character() { + return faker.fakeValuesService().resolve("dragon_ball.characters", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Dune.java b/src/main/java/org/thejavaguy/javafaker/Dune.java index 11cda5b..84d3bf1 100644 --- a/src/main/java/org/thejavaguy/javafaker/Dune.java +++ b/src/main/java/org/thejavaguy/javafaker/Dune.java @@ -2,79 +2,78 @@ public class Dune { - private final Faker faker; - - protected Dune(Faker faker) { - this.faker = faker; - } - - public String character() { - return faker.fakeValuesService().resolve("dune.characters", this, faker); - } - - public String title() { - return faker.fakeValuesService().resolve("dune.titles", this, faker); - } - - public String planet() { - return faker.fakeValuesService().resolve("dune.planets", this, faker); - } - - public String quote() { - return quote(faker.options().option(Dune.Quote.class)); + private final Faker faker; + + protected Dune(Faker faker) { + this.faker = faker; + } + + public String character() { + return faker.fakeValuesService().resolve("dune.characters", this, faker); + } + + public String title() { + return faker.fakeValuesService().resolve("dune.titles", this, faker); + } + + public String planet() { + return faker.fakeValuesService().resolve("dune.planets", this, faker); + } + + public String quote() { + return quote(faker.options().option(Dune.Quote.class)); + } + + public String quote(Quote quote) { + return faker.fakeValuesService().resolve("dune.quotes." + quote.yamlKey, this, faker); + } + + public String saying() { + return saying(faker.options().option(Dune.Saying.class)); + } + + public String saying(Saying saying) { + return faker.fakeValuesService().resolve("dune.sayings." + saying.yamlKey, this, faker); + } + + public enum Quote { + GUILD_NAIVGATOR("guild_navigator"), + EMPEROR("emperor"), + PAUL("paul"), + THUFIR("thufir"), + JESSICA("jessica"), + IRULAN("irulan"), + MOHIAM("mohiam"), + GURNEY("gurney"), + LETO("leto"), + STILGAR("stilgar"), + LIET_KYNES("liet_kynes"), + PARDOT_KYNES("pardot_kynes"), + BARON_HARKONNEN("baron_harkonnen"), + PITER("piter"), + ALIA("alia"), + MAPES("mapes"), + DUNCAN("duncan"), + YUEH("yueh"); + + private final String yamlKey; + + Quote(String yamlKey) { + this.yamlKey = yamlKey; } + } - public String quote(Quote quote) { - return faker.fakeValuesService().resolve("dune.quotes." + quote.yamlKey, this, faker); - } + public enum Saying { + BENE_GESSERIT("bene_gesserit"), + FREMEN("fremen"), + MENTAT("mentat"), + MUADDIB("muaddib"), + ORANGE_CATHOLIC_BIBLE("orange_catholic_bible"); - public String saying() { - return saying(faker.options().option(Dune.Saying.class)); - } + private final String yamlKey; - public String saying(Saying saying) { - return faker.fakeValuesService().resolve("dune.sayings." + saying.yamlKey, this, faker); + Saying(String yamlKey) { + this.yamlKey = yamlKey; } - - public enum Quote { - GUILD_NAIVGATOR("guild_navigator"), - EMPEROR("emperor"), - PAUL("paul"), - THUFIR("thufir"), - JESSICA("jessica"), - IRULAN("irulan"), - MOHIAM("mohiam"), - GURNEY("gurney"), - LETO("leto"), - STILGAR("stilgar"), - LIET_KYNES("liet_kynes"), - PARDOT_KYNES("pardot_kynes"), - BARON_HARKONNEN("baron_harkonnen"), - PITER("piter"), - ALIA("alia"), - MAPES("mapes"), - DUNCAN("duncan"), - YUEH("yueh"); - - private final String yamlKey; - - Quote(String yamlKey) { - this.yamlKey = yamlKey; - } - } - - public enum Saying { - BENE_GESSERIT("bene_gesserit"), - FREMEN("fremen"), - MENTAT("mentat"), - MUADDIB("muaddib"), - ORANGE_CATHOLIC_BIBLE("orange_catholic_bible"); - - private final String yamlKey; - - Saying(String yamlKey) { - this.yamlKey = yamlKey; - } - } - + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Educator.java b/src/main/java/org/thejavaguy/javafaker/Educator.java index a3511d9..dc341ee 100644 --- a/src/main/java/org/thejavaguy/javafaker/Educator.java +++ b/src/main/java/org/thejavaguy/javafaker/Educator.java @@ -1,33 +1,32 @@ package org.thejavaguy.javafaker; public class Educator { - private final Faker faker; + private final Faker faker; - protected Educator(Faker faker) { - this.faker = faker; - } + protected Educator(Faker faker) { + this.faker = faker; + } - // TODO - move these all out to en.yml by default. - public String university() { - return faker.fakeValuesService().resolve("educator.name", this, faker) - + " " - + faker.fakeValuesService().resolve("educator.tertiary.type", this, faker); - } + // TODO - move these all out to en.yml by default. + public String university() { + return faker.fakeValuesService().resolve("educator.name", this, faker) + + " " + + faker.fakeValuesService().resolve("educator.tertiary.type", this, faker); + } - public String course() { - return faker.fakeValuesService().resolve("educator.tertiary.degree.type", this, faker) - + " " - + faker.fakeValuesService().resolve("educator.tertiary.degree.subject", this, faker); - } + public String course() { + return faker.fakeValuesService().resolve("educator.tertiary.degree.type", this, faker) + + " " + + faker.fakeValuesService().resolve("educator.tertiary.degree.subject", this, faker); + } - public String secondarySchool() { - return faker.fakeValuesService().resolve("educator.name", this, faker) - + " " - + faker.fakeValuesService().resolve("educator.secondary", this, faker); - } - - public String campus() { - return faker.fakeValuesService().resolve("educator.name", this, faker) + " Campus"; - } + public String secondarySchool() { + return faker.fakeValuesService().resolve("educator.name", this, faker) + + " " + + faker.fakeValuesService().resolve("educator.secondary", this, faker); + } + public String campus() { + return faker.fakeValuesService().resolve("educator.name", this, faker) + " Campus"; + } } diff --git a/src/main/java/org/thejavaguy/javafaker/ElderScrolls.java b/src/main/java/org/thejavaguy/javafaker/ElderScrolls.java index e241b52..c14b57a 100644 --- a/src/main/java/org/thejavaguy/javafaker/ElderScrolls.java +++ b/src/main/java/org/thejavaguy/javafaker/ElderScrolls.java @@ -2,40 +2,41 @@ public class ElderScrolls { - private final Faker faker; + private final Faker faker; - protected ElderScrolls(Faker faker) { - this.faker = faker; - } + protected ElderScrolls(Faker faker) { + this.faker = faker; + } - public String race() { - return faker.fakeValuesService().resolve("games.elder_scrolls.race", this, faker); - } + public String race() { + return faker.fakeValuesService().resolve("games.elder_scrolls.race", this, faker); + } - public String creature() { - return faker.fakeValuesService().resolve("games.elder_scrolls.creature", this, faker); - } + public String creature() { + return faker.fakeValuesService().resolve("games.elder_scrolls.creature", this, faker); + } - public String region() { - return faker.fakeValuesService().resolve("games.elder_scrolls.region", this, faker); - } + public String region() { + return faker.fakeValuesService().resolve("games.elder_scrolls.region", this, faker); + } - public String dragon() { - return faker.fakeValuesService().resolve("games.elder_scrolls.dragon", this, faker); - } + public String dragon() { + return faker.fakeValuesService().resolve("games.elder_scrolls.dragon", this, faker); + } - public String city() { - return faker.fakeValuesService().resolve("games.elder_scrolls.city", this, faker); - } + public String city() { + return faker.fakeValuesService().resolve("games.elder_scrolls.city", this, faker); + } - public String firstName() { - return faker.fakeValuesService().resolve("games.elder_scrolls.first_name", this, faker); - } + public String firstName() { + return faker.fakeValuesService().resolve("games.elder_scrolls.first_name", this, faker); + } - public String lastName() { - return faker.fakeValuesService().resolve("games.elder_scrolls.last_name", this, faker); - } + public String lastName() { + return faker.fakeValuesService().resolve("games.elder_scrolls.last_name", this, faker); + } - public String quote() {return faker.fakeValuesService().resolve("games.elder_scrolls.quote", this, faker); - } + public String quote() { + return faker.fakeValuesService().resolve("games.elder_scrolls.quote", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/EnglandFootBall.java b/src/main/java/org/thejavaguy/javafaker/EnglandFootBall.java index 01028be..01104af 100644 --- a/src/main/java/org/thejavaguy/javafaker/EnglandFootBall.java +++ b/src/main/java/org/thejavaguy/javafaker/EnglandFootBall.java @@ -2,17 +2,17 @@ public class EnglandFootBall { - private final Faker faker; + private final Faker faker; - protected EnglandFootBall(final Faker faker) { - this.faker = faker; - } + protected EnglandFootBall(final Faker faker) { + this.faker = faker; + } - public String league() { - return faker.fakeValuesService().resolve("englandfootball.leagues",this,faker); - } + public String league() { + return faker.fakeValuesService().resolve("englandfootball.leagues", this, faker); + } - public String team() { - return faker.fakeValuesService().resolve("englandfootball.teams",this,faker); - } + public String team() { + return faker.fakeValuesService().resolve("englandfootball.teams", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Esports.java b/src/main/java/org/thejavaguy/javafaker/Esports.java index 3e1766a..9c32947 100644 --- a/src/main/java/org/thejavaguy/javafaker/Esports.java +++ b/src/main/java/org/thejavaguy/javafaker/Esports.java @@ -1,29 +1,29 @@ package org.thejavaguy.javafaker; public class Esports { - private final Faker faker; + private final Faker faker; - protected Esports(final Faker faker) { - this.faker = faker; - } + protected Esports(final Faker faker) { + this.faker = faker; + } - public String player() { - return faker.resolve("esport.players"); - } + public String player() { + return faker.resolve("esport.players"); + } - public String team() { - return faker.resolve("esport.teams"); - } + public String team() { + return faker.resolve("esport.teams"); + } - public String event() { - return faker.resolve("esport.events"); - } + public String event() { + return faker.resolve("esport.events"); + } - public String league() { - return faker.resolve("esport.leagues"); - } + public String league() { + return faker.resolve("esport.leagues"); + } - public String game() { - return faker.resolve("esport.games"); - } + public String game() { + return faker.resolve("esport.games"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Faker.java b/src/main/java/org/thejavaguy/javafaker/Faker.java index edc3935..4e708dd 100644 --- a/src/main/java/org/thejavaguy/javafaker/Faker.java +++ b/src/main/java/org/thejavaguy/javafaker/Faker.java @@ -2,738 +2,752 @@ import java.util.Locale; import java.util.Random; - import org.thejavaguy.javafaker.service.FakeValuesService; import org.thejavaguy.javafaker.service.RandomService; /** - * Provides utility methods for generating fake strings, such as names, phone - * numbers, addresses. generate random strings with given patterns + * Provides utility methods for generating fake strings, such as names, phone numbers, addresses. + * generate random strings with given patterns * * @author ren */ public class Faker { - private final RandomService randomService; - private final FakeValuesService fakeValuesService; - - private final Ancient ancient; - private final App app; - private final Artist artist; - private final Avatar avatar; - private final Aviation aviation; - private final Lorem lorem; - private final Music music; - private final Name name; - private final Number number; - private final Internet internet; - private final PhoneNumber phoneNumber; - private final Pokemon pokemon; - private final Address address; - private final Business business; - private final Book book; - private final ChuckNorris chuckNorris; - private final Color color; - private final Commerce commerce; - private final Country country; - private final Currency currency; - private final Company company; - private final Crypto crypto; - private final IdNumber idNumber; - private final Hacker hacker; - private final Options options; - private final Code code; - private final Coin coin; - private final Finance finance; - private final CreditCard creditCard; - private final Food food; - private final GameOfThrones gameOfThrones; - private final Gender gender; - private final DateAndTime dateAndTime; - private final Demographic demographic; - private final Dog dog; - private final Educator educator; - private final ElderScrolls elderScrolls; - private final Shakespeare shakespeare; - private final SlackEmoji slackEmoji; - private final Space space; - private final Superhero superhero; - private final Bool bool; - private final Team team; - private final Beer beer; - private final University university; - private final Cat cat; - private final File file; - private final Stock stock; - private final LordOfTheRings lordOfTheRings; - private final Zelda zelda; - private final HarryPotter harryPotter; - private final RockBand rockBand; - private final Esports esports; - private final Friends friends; - private final Hipster hipster; - private final Job job; - private final TwinPeaks twinPeaks; - private final RickAndMorty rickAndMorty; - private final Yoda yoda; - private final Matz matz; - private final Witcher witcher; - private final DragonBall dragonBall; - private final FunnyName funnyName; - private final HitchhikersGuideToTheGalaxy hitchhikersGuideToTheGalaxy; - private final Hobbit hobbit; - private final HowIMetYourMother howIMetYourMother; - private final LeagueOfLegends leagueOfLegends; - private final Overwatch overwatch; - private final Robin robin; - private final StarTrek starTrek; - private final Weather weather; - private final Lebowski lebowski; - private final Medical medical; - private final Animal animal; - private final BackToTheFuture backToTheFuture; - private final PrincessBride princessBride; - private final Buffy buffy; - private final Relationships relationships; - private final Nation nation; - private final Dune dune; - private final AquaTeenHungerForce aquaTeenHungerForce; - private final ProgrammingLanguage programmingLanguage; - private final Kaamelott kaamelott; - private final Photography photography; - private final StarCraft starCraft; - private final BojackHorseman bojackHorseman; - private final Disease disease; - private final Basketball basketball; - private final Barcode barcode; - private final Sip sip; - private final EnglandFootBall englandfootball; - private final Mountain mountain; - private final Shipping shipping; - - public Faker() { - this(Locale.ENGLISH); - } - - public Faker(Locale locale) { - this(locale, (Random)null); - } - - public Faker(Random random) { - this(Locale.ENGLISH, random); - } - - public Faker(Locale locale, Random random) { - this(locale, new RandomService(random)); - } - - public Faker(Locale locale, RandomService randomService) { - this(new FakeValuesService(locale, randomService), randomService); - } - - public Faker(FakeValuesService fakeValuesService, RandomService random) { - this.randomService = random; - this.fakeValuesService = fakeValuesService; - - this.ancient = new Ancient(this); - this.app = new App(this); - this.artist = new Artist(this); - this.avatar = new Avatar(this); - this.aviation = new Aviation(this); - this.lorem = new Lorem(this); - this.music = new Music(this); - this.name = new Name(this); - this.number = new Number(this); - this.internet = new Internet(this); - this.phoneNumber = new PhoneNumber(this); - this.pokemon = new Pokemon(this); - this.address = new Address(this); - this.book = new Book(this); - this.business = new Business(this); - this.chuckNorris = new ChuckNorris(this); - this.color = new Color(this); - this.idNumber = new IdNumber(this); - this.hacker = new Hacker(this); - this.company = new Company(this); - this.crypto = new Crypto(this); - this.elderScrolls = new ElderScrolls(this); - this.commerce = new Commerce(this); - this.currency = new Currency(this); - this.options = new Options(this); - this.code = new Code(this); - this.file = new File(this); - this.finance = new Finance(this); - this.creditCard = new CreditCard(this); - this.food = new Food(this); - this.gameOfThrones = new GameOfThrones(this); - this.gender = new Gender(this); - this.dateAndTime = new DateAndTime(this); - this.demographic = new Demographic(this); - this.dog = new Dog(this); - this.educator = new Educator(this); - this.shakespeare = new Shakespeare(this); - this.slackEmoji = new SlackEmoji(this); - this.space = new Space(this); - this.coin = new Coin(this); - this.superhero = new Superhero(this); - this.team = new Team(this); - this.bool = new Bool(this); - this.beer = new Beer(this); - this.university = new University(this); - this.cat = new Cat(this); - this.stock = new Stock(this); - this.lordOfTheRings = new LordOfTheRings(this); - this.zelda = new Zelda(this); - this.harryPotter = new HarryPotter(this); - this.rockBand = new RockBand(this); - this.esports = new Esports(this); - this.friends = new Friends(this); - this.hipster = new Hipster(this); - this.job = new Job(this); - this.twinPeaks = new TwinPeaks(this); - this.rickAndMorty = new RickAndMorty(this); - this.yoda = new Yoda(this); - this.matz = new Matz(this); - this.witcher = new Witcher(this); - this.dragonBall = new DragonBall(this); - this.funnyName = new FunnyName(this); - this.hitchhikersGuideToTheGalaxy = new HitchhikersGuideToTheGalaxy(this); - this.hobbit = new Hobbit(this); - this.howIMetYourMother = new HowIMetYourMother(this); - this.leagueOfLegends = new LeagueOfLegends(this); - this.overwatch = new Overwatch(this); - this.robin = new Robin(this); - this.starTrek = new StarTrek(this); - this.weather = new Weather(this); - this.lebowski = new Lebowski(this); - this.medical = new Medical(this); - this.country = new Country(this); - this.animal = new Animal(this); - this.backToTheFuture = new BackToTheFuture(this); - this.princessBride = new PrincessBride(this); - this.buffy = new Buffy(this); - this.relationships = new Relationships(this); - this.nation = new Nation(this); - this.dune = new Dune(this); - this.aquaTeenHungerForce = new AquaTeenHungerForce(this); - this.programmingLanguage = new ProgrammingLanguage(this); - this.kaamelott = new Kaamelott(this); - this.photography = new Photography(this); - this.starCraft = new StarCraft(this); - this.bojackHorseman = new BojackHorseman(this); - this.disease = new Disease(this); - this.basketball = new Basketball(this); - this.barcode = new Barcode(this); - this.sip = new Sip(this); - this.englandfootball = new EnglandFootBall(this); - this.mountain = new Mountain(this); - this.shipping = new Shipping(this); - } - - /** - * Constructs Faker instance with default argument. - * - * @return {@link Faker#Faker()} - */ - public static Faker instance() { - return new Faker(); - } - - /** - * Constructs Faker instance with provided {@link Locale}. - * - * @param locale - {@link Locale} - * @return {@link Faker#Faker(Locale)} - */ - public static Faker instance(Locale locale) { - return new Faker(locale); - } - - /** - * Constructs Faker instance with provided {@link Random}. - * - * @param random - {@link Random} - * @return {@link Faker#Faker(Random)} - */ - public static Faker instance(Random random) { - return new Faker(random); - } - - /** - * Constructs Faker instance with provided {@link Locale} and {@link Random}. - * - * @param locale - {@link Locale} - * @param random - {@link Random} - * @return {@link Faker#Faker(Locale, Random)} - */ - public static Faker instance(Locale locale, Random random) { - return new Faker(locale, random); - } - - /** - * Returns a string with the '#' characters in the parameter replaced with random digits between 0-9 inclusive. - *

- * For example, the string "ABC##EFG" could be replaced with a string like "ABC99EFG". - * - * @param numberString - * @return - */ - public String numerify(String numberString) { - return fakeValuesService.numerify(numberString); - } - - /** - * Returns a string with the '?' characters in the parameter replaced with random alphabetic - * characters. - *

- * For example, the string "12??34" could be replaced with a string like "12AB34". - * - * @param letterString - * @return - */ - public String letterify(String letterString) { - return fakeValuesService.letterify(letterString); - } - - /** - * Returns a string with the '?' characters in the parameter replaced with random alphabetic - * characters. - *

- * For example, the string "12??34" could be replaced with a string like "12AB34". - * - * @param letterString - * @param isUpper - * @return - */ - public String letterify(String letterString, boolean isUpper) { - return fakeValuesService.letterify(letterString, isUpper); - } - - /** - * Applies both a {@link #numerify(String)} and a {@link #letterify(String)} - * over the incoming string. - * - * @param string - * @return - */ - public String bothify(String string) { - return fakeValuesService.bothify(string); - } - - /** - * Applies both a {@link #numerify(String)} and a {@link #letterify(String)} - * over the incoming string. - * - * @param string - * @param isUpper - * @return - */ - public String bothify(String string, boolean isUpper) { - return fakeValuesService.bothify(string, isUpper); - } - - /** - * Generates a String that matches the given regular expression. - */ - public String regexify(String regex) { - return fakeValuesService.regexify(regex); - } - - public RandomService random() { - return this.randomService; - } - - public Currency currency() { - return currency; - - } - - FakeValuesService fakeValuesService() { - return this.fakeValuesService; - } - - public Ancient ancient() { - return ancient; - } - - public App app() { - return app; - } - - public Artist artist() { - return artist; - } - - public Avatar avatar() { - return avatar; - } - - public Aviation aviation() { - return aviation; - } - - public Music music() { - return music; - } - - public Name name() { - return name; - } - - public Number number() { - return number; - } - - public Internet internet() { - return internet; - } - - public PhoneNumber phoneNumber() { - return phoneNumber; - } - - public Pokemon pokemon() { - return pokemon; - } - - public Lorem lorem() { - return lorem; - } - - public Address address() { - return address; - } - - public Book book() { - return book; - } - - public Buffy buffy() { - return buffy; - } - - public Business business() { - return business; - } - - public ChuckNorris chuckNorris() { - return chuckNorris; - } - - public Color color() { - return color; - } - - public Commerce commerce() { - return commerce; - } - - public Company company() { - return company; - } - - public Crypto crypto() { - return crypto; - } - - public Hacker hacker() { - return hacker; - } - - public IdNumber idNumber() { - return idNumber; - } - - public Options options() { - return options; - } - - public Code code() { - return code; - } - - public Coin coin() { - return coin; - } - - public File file() { - return file; - } - - public Finance finance() { - return finance; - } - - /** - * Returns a CreditCard instance for generating credit card fake data. - * - * @return a {@link CreditCard} instance - */ - public CreditCard creditCard() { - return creditCard; - } - - public Food food() { - return food; - } - - public ElderScrolls elderScrolls() { - return elderScrolls; - } - - public GameOfThrones gameOfThrones() { - return gameOfThrones; - } - - public Gender gender() { - return gender; - } - - public DateAndTime date() { - return dateAndTime; - } - - public Demographic demographic() { - return demographic; - } - - public Dog dog() { - return dog; - } - - public Educator educator() { - return educator; - } - - public SlackEmoji slackEmoji() { - return slackEmoji; - } - - public Shakespeare shakespeare() { - return shakespeare; - } - - public Space space() { - return space; - } - - public Superhero superhero() { - return superhero; - } - - public Bool bool() { - return bool; - } - - public Team team() { - return team; - } - - public Beer beer() { return beer; } - - public University university() { - return university; - } - - public Cat cat() { - return cat; - } - - public Stock stock() { - return stock; - } - - public LordOfTheRings lordOfTheRings() { - return lordOfTheRings; - } - - public Zelda zelda() { - return zelda; - } - - public HarryPotter harryPotter() { - return harryPotter; - } - - public RockBand rockBand() { - return rockBand; - } - - public Esports esports() { - return esports; - } - - public Friends friends() { - return friends; - } - - public Hipster hipster() { - return hipster; - } - - public Job job() { - return job; - } + private final RandomService randomService; + private final FakeValuesService fakeValuesService; + + private final Ancient ancient; + private final App app; + private final Artist artist; + private final Avatar avatar; + private final Aviation aviation; + private final Lorem lorem; + private final Music music; + private final Name name; + private final Number number; + private final Internet internet; + private final PhoneNumber phoneNumber; + private final Pokemon pokemon; + private final Address address; + private final Business business; + private final Book book; + private final ChuckNorris chuckNorris; + private final Color color; + private final Commerce commerce; + private final Country country; + private final Currency currency; + private final Company company; + private final Crypto crypto; + private final IdNumber idNumber; + private final Hacker hacker; + private final Options options; + private final Code code; + private final Coin coin; + private final Finance finance; + private final CreditCard creditCard; + private final Food food; + private final GameOfThrones gameOfThrones; + private final Gender gender; + private final DateAndTime dateAndTime; + private final Demographic demographic; + private final Dog dog; + private final Educator educator; + private final ElderScrolls elderScrolls; + private final Shakespeare shakespeare; + private final SlackEmoji slackEmoji; + private final Space space; + private final Superhero superhero; + private final Bool bool; + private final Team team; + private final Beer beer; + private final University university; + private final Cat cat; + private final File file; + private final Stock stock; + private final LordOfTheRings lordOfTheRings; + private final Zelda zelda; + private final HarryPotter harryPotter; + private final RockBand rockBand; + private final Esports esports; + private final Friends friends; + private final Hipster hipster; + private final Job job; + private final TwinPeaks twinPeaks; + private final RickAndMorty rickAndMorty; + private final Yoda yoda; + private final Matz matz; + private final Witcher witcher; + private final DragonBall dragonBall; + private final FunnyName funnyName; + private final HitchhikersGuideToTheGalaxy hitchhikersGuideToTheGalaxy; + private final Hobbit hobbit; + private final HowIMetYourMother howIMetYourMother; + private final LeagueOfLegends leagueOfLegends; + private final Overwatch overwatch; + private final Robin robin; + private final StarTrek starTrek; + private final Weather weather; + private final Lebowski lebowski; + private final Medical medical; + private final Animal animal; + private final BackToTheFuture backToTheFuture; + private final PrincessBride princessBride; + private final Buffy buffy; + private final Relationships relationships; + private final Nation nation; + private final Dune dune; + private final AquaTeenHungerForce aquaTeenHungerForce; + private final ProgrammingLanguage programmingLanguage; + private final Kaamelott kaamelott; + private final Photography photography; + private final StarCraft starCraft; + private final BojackHorseman bojackHorseman; + private final Disease disease; + private final Basketball basketball; + private final Barcode barcode; + private final Sip sip; + private final EnglandFootBall englandfootball; + private final Mountain mountain; + private final Shipping shipping; + + public Faker() { + this(Locale.ENGLISH); + } + + public Faker(Locale locale) { + this(locale, (Random) null); + } + + public Faker(Random random) { + this(Locale.ENGLISH, random); + } + + public Faker(Locale locale, Random random) { + this(locale, new RandomService(random)); + } + + public Faker(Locale locale, RandomService randomService) { + this(new FakeValuesService(locale, randomService), randomService); + } + + public Faker(FakeValuesService fakeValuesService, RandomService random) { + this.randomService = random; + this.fakeValuesService = fakeValuesService; + + this.ancient = new Ancient(this); + this.app = new App(this); + this.artist = new Artist(this); + this.avatar = new Avatar(this); + this.aviation = new Aviation(this); + this.lorem = new Lorem(this); + this.music = new Music(this); + this.name = new Name(this); + this.number = new Number(this); + this.internet = new Internet(this); + this.phoneNumber = new PhoneNumber(this); + this.pokemon = new Pokemon(this); + this.address = new Address(this); + this.book = new Book(this); + this.business = new Business(this); + this.chuckNorris = new ChuckNorris(this); + this.color = new Color(this); + this.idNumber = new IdNumber(this); + this.hacker = new Hacker(this); + this.company = new Company(this); + this.crypto = new Crypto(this); + this.elderScrolls = new ElderScrolls(this); + this.commerce = new Commerce(this); + this.currency = new Currency(this); + this.options = new Options(this); + this.code = new Code(this); + this.file = new File(this); + this.finance = new Finance(this); + this.creditCard = new CreditCard(this); + this.food = new Food(this); + this.gameOfThrones = new GameOfThrones(this); + this.gender = new Gender(this); + this.dateAndTime = new DateAndTime(this); + this.demographic = new Demographic(this); + this.dog = new Dog(this); + this.educator = new Educator(this); + this.shakespeare = new Shakespeare(this); + this.slackEmoji = new SlackEmoji(this); + this.space = new Space(this); + this.coin = new Coin(this); + this.superhero = new Superhero(this); + this.team = new Team(this); + this.bool = new Bool(this); + this.beer = new Beer(this); + this.university = new University(this); + this.cat = new Cat(this); + this.stock = new Stock(this); + this.lordOfTheRings = new LordOfTheRings(this); + this.zelda = new Zelda(this); + this.harryPotter = new HarryPotter(this); + this.rockBand = new RockBand(this); + this.esports = new Esports(this); + this.friends = new Friends(this); + this.hipster = new Hipster(this); + this.job = new Job(this); + this.twinPeaks = new TwinPeaks(this); + this.rickAndMorty = new RickAndMorty(this); + this.yoda = new Yoda(this); + this.matz = new Matz(this); + this.witcher = new Witcher(this); + this.dragonBall = new DragonBall(this); + this.funnyName = new FunnyName(this); + this.hitchhikersGuideToTheGalaxy = new HitchhikersGuideToTheGalaxy(this); + this.hobbit = new Hobbit(this); + this.howIMetYourMother = new HowIMetYourMother(this); + this.leagueOfLegends = new LeagueOfLegends(this); + this.overwatch = new Overwatch(this); + this.robin = new Robin(this); + this.starTrek = new StarTrek(this); + this.weather = new Weather(this); + this.lebowski = new Lebowski(this); + this.medical = new Medical(this); + this.country = new Country(this); + this.animal = new Animal(this); + this.backToTheFuture = new BackToTheFuture(this); + this.princessBride = new PrincessBride(this); + this.buffy = new Buffy(this); + this.relationships = new Relationships(this); + this.nation = new Nation(this); + this.dune = new Dune(this); + this.aquaTeenHungerForce = new AquaTeenHungerForce(this); + this.programmingLanguage = new ProgrammingLanguage(this); + this.kaamelott = new Kaamelott(this); + this.photography = new Photography(this); + this.starCraft = new StarCraft(this); + this.bojackHorseman = new BojackHorseman(this); + this.disease = new Disease(this); + this.basketball = new Basketball(this); + this.barcode = new Barcode(this); + this.sip = new Sip(this); + this.englandfootball = new EnglandFootBall(this); + this.mountain = new Mountain(this); + this.shipping = new Shipping(this); + } + + /** + * Constructs Faker instance with default argument. + * + * @return {@link Faker#Faker()} + */ + public static Faker instance() { + return new Faker(); + } + + /** + * Constructs Faker instance with provided {@link Locale}. + * + * @param locale - {@link Locale} + * @return {@link Faker#Faker(Locale)} + */ + public static Faker instance(Locale locale) { + return new Faker(locale); + } + + /** + * Constructs Faker instance with provided {@link Random}. + * + * @param random - {@link Random} + * @return {@link Faker#Faker(Random)} + */ + public static Faker instance(Random random) { + return new Faker(random); + } + + /** + * Constructs Faker instance with provided {@link Locale} and {@link Random}. + * + * @param locale - {@link Locale} + * @param random - {@link Random} + * @return {@link Faker#Faker(Locale, Random)} + */ + public static Faker instance(Locale locale, Random random) { + return new Faker(locale, random); + } + + /** + * Returns a string with the '#' characters in the parameter replaced with random digits between + * 0-9 inclusive. + * + *

For example, the string "ABC##EFG" could be replaced with a string like "ABC99EFG". + * + * @param numberString + * @return + */ + public String numerify(String numberString) { + return fakeValuesService.numerify(numberString); + } + + /** + * Returns a string with the '?' characters in the parameter replaced with random alphabetic + * characters. + * + *

For example, the string "12??34" could be replaced with a string like "12AB34". + * + * @param letterString + * @return + */ + public String letterify(String letterString) { + return fakeValuesService.letterify(letterString); + } + + /** + * Returns a string with the '?' characters in the parameter replaced with random alphabetic + * characters. + * + *

For example, the string "12??34" could be replaced with a string like "12AB34". + * + * @param letterString + * @param isUpper + * @return + */ + public String letterify(String letterString, boolean isUpper) { + return fakeValuesService.letterify(letterString, isUpper); + } + + /** + * Applies both a {@link #numerify(String)} and a {@link #letterify(String)} over the incoming + * string. + * + * @param string + * @return + */ + public String bothify(String string) { + return fakeValuesService.bothify(string); + } + + /** + * Applies both a {@link #numerify(String)} and a {@link #letterify(String)} over the incoming + * string. + * + * @param string + * @param isUpper + * @return + */ + public String bothify(String string, boolean isUpper) { + return fakeValuesService.bothify(string, isUpper); + } + + /** Generates a String that matches the given regular expression. */ + public String regexify(String regex) { + return fakeValuesService.regexify(regex); + } + + public RandomService random() { + return this.randomService; + } + + public Currency currency() { + return currency; + } + + FakeValuesService fakeValuesService() { + return this.fakeValuesService; + } + + public Ancient ancient() { + return ancient; + } + + public App app() { + return app; + } + + public Artist artist() { + return artist; + } + + public Avatar avatar() { + return avatar; + } + + public Aviation aviation() { + return aviation; + } + + public Music music() { + return music; + } + + public Name name() { + return name; + } + + public Number number() { + return number; + } + + public Internet internet() { + return internet; + } + + public PhoneNumber phoneNumber() { + return phoneNumber; + } + + public Pokemon pokemon() { + return pokemon; + } + + public Lorem lorem() { + return lorem; + } + + public Address address() { + return address; + } + + public Book book() { + return book; + } + + public Buffy buffy() { + return buffy; + } + + public Business business() { + return business; + } + + public ChuckNorris chuckNorris() { + return chuckNorris; + } + + public Color color() { + return color; + } + + public Commerce commerce() { + return commerce; + } + + public Company company() { + return company; + } + + public Crypto crypto() { + return crypto; + } + + public Hacker hacker() { + return hacker; + } + + public IdNumber idNumber() { + return idNumber; + } + + public Options options() { + return options; + } + + public Code code() { + return code; + } + + public Coin coin() { + return coin; + } + + public File file() { + return file; + } + + public Finance finance() { + return finance; + } + + /** + * Returns a CreditCard instance for generating credit card fake data. + * + * @return a {@link CreditCard} instance + */ + public CreditCard creditCard() { + return creditCard; + } + + public Food food() { + return food; + } + + public ElderScrolls elderScrolls() { + return elderScrolls; + } + + public GameOfThrones gameOfThrones() { + return gameOfThrones; + } + + public Gender gender() { + return gender; + } + + public DateAndTime date() { + return dateAndTime; + } + + public Demographic demographic() { + return demographic; + } + + public Dog dog() { + return dog; + } + + public Educator educator() { + return educator; + } + + public SlackEmoji slackEmoji() { + return slackEmoji; + } + + public Shakespeare shakespeare() { + return shakespeare; + } + + public Space space() { + return space; + } + + public Superhero superhero() { + return superhero; + } + + public Bool bool() { + return bool; + } + + public Team team() { + return team; + } + + public Beer beer() { + return beer; + } + + public University university() { + return university; + } + + public Cat cat() { + return cat; + } + + public Stock stock() { + return stock; + } + + public LordOfTheRings lordOfTheRings() { + return lordOfTheRings; + } + + public Zelda zelda() { + return zelda; + } + + public HarryPotter harryPotter() { + return harryPotter; + } + + public RockBand rockBand() { + return rockBand; + } + + public Esports esports() { + return esports; + } + + public Friends friends() { + return friends; + } - public TwinPeaks twinPeaks() { - return twinPeaks; - } + public Hipster hipster() { + return hipster; + } - public RickAndMorty rickAndMorty() { - return rickAndMorty; - } + public Job job() { + return job; + } - public Yoda yoda() { - return yoda; - } + public TwinPeaks twinPeaks() { + return twinPeaks; + } - public Matz matz() { - return matz; - } + public RickAndMorty rickAndMorty() { + return rickAndMorty; + } - public Witcher witcher() { - return witcher; - } + public Yoda yoda() { + return yoda; + } - public DragonBall dragonBall() { - return dragonBall; - } + public Matz matz() { + return matz; + } - public FunnyName funnyName() { - return funnyName; - } + public Witcher witcher() { + return witcher; + } - public HitchhikersGuideToTheGalaxy hitchhikersGuideToTheGalaxy() { - return hitchhikersGuideToTheGalaxy; - } + public DragonBall dragonBall() { + return dragonBall; + } - public Hobbit hobbit() { - return hobbit; - } + public FunnyName funnyName() { + return funnyName; + } - public HowIMetYourMother howIMetYourMother() { - return howIMetYourMother; - } + public HitchhikersGuideToTheGalaxy hitchhikersGuideToTheGalaxy() { + return hitchhikersGuideToTheGalaxy; + } - public LeagueOfLegends leagueOfLegends() { - return leagueOfLegends; - } + public Hobbit hobbit() { + return hobbit; + } - public Overwatch overwatch() { - return overwatch; - } + public HowIMetYourMother howIMetYourMother() { + return howIMetYourMother; + } - public Robin robin() { - return robin; - } + public LeagueOfLegends leagueOfLegends() { + return leagueOfLegends; + } - public StarTrek starTrek() { - return starTrek; - } + public Overwatch overwatch() { + return overwatch; + } - public Weather weather() { - return weather; - } - - public Lebowski lebowski() { - return lebowski; - } - - public Medical medical() { - return medical; - } - - public Country country() { - return country; - } - - public Animal animal() { - return animal; - } - - public BackToTheFuture backToTheFuture() { - return backToTheFuture; - } - - public PrincessBride princessBride() { - return princessBride; - } - - public Relationships relationships() { - return relationships; - } - - public Nation nation() { - return nation; - } - - public Dune dune() { - return dune; - } - - public AquaTeenHungerForce aquaTeenHungerForce() { - return aquaTeenHungerForce; - } - - public ProgrammingLanguage programmingLanguage() { - return programmingLanguage; - } - - public Kaamelott kaamelott() { - return kaamelott; - } - - public Photography photography() { - return photography; - } - - public StarCraft starCraft() { - return starCraft; - } - - public BojackHorseman bojackHorseman() { return bojackHorseman; } - - public Disease disease() {return disease; } - - public Basketball basketball() { return basketball; } - - public Barcode barcode() { return barcode; } - - public Sip sip() { return sip; } - - public EnglandFootBall englandfootball() { return englandfootball; } - - public Mountain mountain() { return mountain; } - - /** - * Returns a Shipping instance for generating shipping-related fake data. - * - * @return a {@link Shipping} instance - */ - public Shipping shipping() { - return shipping; - } - - public String resolve(String key) { - return this.fakeValuesService.resolve(key, this, this); - } - - /** - * Allows the evaluation of native YML expressions to allow you to build your own. - *

- * The following are valid expressions: - *

    - *
  • #{regexify '(a|b){2,3}'}
  • - *
  • #{regexify '\\.\\*\\?\\+'}
  • - *
  • #{bothify '????','false'}
  • - *
  • #{Name.first_name} #{Name.first_name} #{Name.last_name}
  • - *
  • #{number.number_between '1','10'}
  • - *
- * - * @param expression (see examples above) - * @return the evaluated string expression - * @throws RuntimeException if unable to evaluate the expression - */ - public String expression(String expression) { - return this.fakeValuesService.expression(expression, this); - } + public Robin robin() { + return robin; + } + + public StarTrek starTrek() { + return starTrek; + } + + public Weather weather() { + return weather; + } + + public Lebowski lebowski() { + return lebowski; + } + + public Medical medical() { + return medical; + } + + public Country country() { + return country; + } + + public Animal animal() { + return animal; + } + + public BackToTheFuture backToTheFuture() { + return backToTheFuture; + } + + public PrincessBride princessBride() { + return princessBride; + } + + public Relationships relationships() { + return relationships; + } + + public Nation nation() { + return nation; + } + + public Dune dune() { + return dune; + } + + public AquaTeenHungerForce aquaTeenHungerForce() { + return aquaTeenHungerForce; + } + + public ProgrammingLanguage programmingLanguage() { + return programmingLanguage; + } + + public Kaamelott kaamelott() { + return kaamelott; + } + + public Photography photography() { + return photography; + } + + public StarCraft starCraft() { + return starCraft; + } + + public BojackHorseman bojackHorseman() { + return bojackHorseman; + } + + public Disease disease() { + return disease; + } + + public Basketball basketball() { + return basketball; + } + + public Barcode barcode() { + return barcode; + } + + public Sip sip() { + return sip; + } + + public EnglandFootBall englandfootball() { + return englandfootball; + } + + public Mountain mountain() { + return mountain; + } + + /** + * Returns a Shipping instance for generating shipping-related fake data. + * + * @return a {@link Shipping} instance + */ + public Shipping shipping() { + return shipping; + } + + public String resolve(String key) { + return this.fakeValuesService.resolve(key, this, this); + } + + /** + * Allows the evaluation of native YML expressions to allow you to build your own. + * + *

The following are valid expressions: + * + *

    + *
  • #{regexify '(a|b){2,3}'} + *
  • #{regexify '\\.\\*\\?\\+'} + *
  • #{bothify '????','false'} + *
  • #{Name.first_name} #{Name.first_name} #{Name.last_name} + *
  • #{number.number_between '1','10'} + *
+ * + * @param expression (see examples above) + * @return the evaluated string expression + * @throws RuntimeException if unable to evaluate the expression + */ + public String expression(String expression) { + return this.fakeValuesService.expression(expression, this); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/File.java b/src/main/java/org/thejavaguy/javafaker/File.java index 8549ec9..d617e6e 100644 --- a/src/main/java/org/thejavaguy/javafaker/File.java +++ b/src/main/java/org/thejavaguy/javafaker/File.java @@ -1,29 +1,31 @@ package org.thejavaguy.javafaker; public class File { - private final Faker faker; + private final Faker faker; - protected File(Faker faker) { - this.faker = faker; - } + protected File(Faker faker) { + this.faker = faker; + } - public String extension() { - return faker.resolve("file.extension"); - } + public String extension() { + return faker.resolve("file.extension"); + } - public String mimeType() { - return faker.resolve("file.mime_type"); - } + public String mimeType() { + return faker.resolve("file.mime_type"); + } - public String fileName() { - return fileName(null, null, null, null); - } + public String fileName() { + return fileName(null, null, null, null); + } - public String fileName(String dirOrNull, String nameOrNull, String extensionOrNull, String separatorOrNull) { - final String sep = separatorOrNull == null ? System.getProperty("file.separator") : separatorOrNull; - final String dir = dirOrNull == null ? faker.internet().slug() : dirOrNull; - final String name = nameOrNull == null ? faker.lorem().word().toLowerCase() : nameOrNull; - final String ext = extensionOrNull == null ? extension() : extensionOrNull; - return dir + sep + name + "." + ext; - } + public String fileName( + String dirOrNull, String nameOrNull, String extensionOrNull, String separatorOrNull) { + final String sep = + separatorOrNull == null ? System.getProperty("file.separator") : separatorOrNull; + final String dir = dirOrNull == null ? faker.internet().slug() : dirOrNull; + final String name = nameOrNull == null ? faker.lorem().word().toLowerCase() : nameOrNull; + final String ext = extensionOrNull == null ? extension() : extensionOrNull; + return dir + sep + name + "." + ext; + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Finance.java b/src/main/java/org/thejavaguy/javafaker/Finance.java index f646228..cdd78f1 100644 --- a/src/main/java/org/thejavaguy/javafaker/Finance.java +++ b/src/main/java/org/thejavaguy/javafaker/Finance.java @@ -5,169 +5,172 @@ import java.util.HashMap; import java.util.List; import java.util.Map; - import org.apache.commons.lang3.StringUtils; public class Finance { - private final Faker faker; - - protected Finance(Faker faker) { - this.faker = faker; + private final Faker faker; + + protected Finance(Faker faker) { + this.faker = faker; + } + + private static final Map countryCodeToBasicBankAccountNumberPattern = + createCountryCodeToBasicBankAccountNumberPatternMap(); + + public String creditCard(CreditCardType creditCardType) { + final String key = + String.format("finance.credit_card.%s", creditCardType.toString().toLowerCase()); + String value = faker.fakeValuesService().resolve(key, this, faker); + final String template = faker.numerify(value); + + String[] split = template.replaceAll("[^0-9]", "").split(""); + List reversedAsInt = new ArrayList<>(); + for (int i = 0; i < split.length; i++) { + final String current = split[split.length - 1 - i]; + if (!current.isEmpty()) { + reversedAsInt.add(Integer.valueOf(current)); + } } - - - private static final Map countryCodeToBasicBankAccountNumberPattern = - createCountryCodeToBasicBankAccountNumberPatternMap(); - - public String creditCard(CreditCardType creditCardType) { - final String key = String.format("finance.credit_card.%s", creditCardType.toString().toLowerCase()); - String value = faker.fakeValuesService().resolve(key, this, faker); - final String template = faker.numerify(value); - - String[] split = template.replaceAll("[^0-9]", "").split(""); - List reversedAsInt = new ArrayList<>(); - for (int i = 0; i < split.length; i++) { - final String current = split[split.length - 1 - i]; - if (!current.isEmpty()) { - reversedAsInt.add(Integer.valueOf(current)); - } - } - int luhnSum = 0; - int multiplier = 1; - for (Integer digit : reversedAsInt) { - multiplier = (multiplier == 2 ? 1 : 2); - luhnSum += sum(String.valueOf(digit * multiplier).split("")); - } - int luhnDigit = (10 - (luhnSum % 10)) % 10; - return template.replace('\\', ' ').replace('/', ' ').trim().replace('L', String.valueOf(luhnDigit).charAt(0)); + int luhnSum = 0; + int multiplier = 1; + for (Integer digit : reversedAsInt) { + multiplier = (multiplier == 2 ? 1 : 2); + luhnSum += sum(String.valueOf(digit * multiplier).split("")); } - - public String creditCard() { - CreditCardType type = randomCreditCardType(); - return creditCard(type); + int luhnDigit = (10 - (luhnSum % 10)) % 10; + return template + .replace('\\', ' ') + .replace('/', ' ') + .trim() + .replace('L', String.valueOf(luhnDigit).charAt(0)); + } + + public String creditCard() { + CreditCardType type = randomCreditCardType(); + return creditCard(type); + } + + /** Generates a random Business Identifier Code */ + public String bic() { + return faker.regexify("([A-Z]){4}([A-Z]){2}([0-9A-Z]){2}([0-9A-Z]{3})?"); + } + + public String iban() { + List countryCodes = + new ArrayList<>(countryCodeToBasicBankAccountNumberPattern.keySet()); + String randomCountryCode = countryCodes.get(faker.random().nextInt(countryCodes.size())); + return iban(randomCountryCode); + } + + public String iban(String countryCode) { + String basicBankAccountNumber = + faker.regexify(countryCodeToBasicBankAccountNumberPattern.get(countryCode)); + String checkSum = calculateIbanChecksum(countryCode, basicBankAccountNumber); + return countryCode + checkSum + basicBankAccountNumber; + } + + private CreditCardType randomCreditCardType() { + return CreditCardType.values()[this.faker.random().nextInt(CreditCardType.values().length)]; + } + + private static int sum(String[] string) { + int sum = 0; + for (String s : string) { + if (!s.isEmpty()) { + sum += Integer.parseInt(s); + } } - - /** - * Generates a random Business Identifier Code - */ - public String bic() { - return faker.regexify("([A-Z]){4}([A-Z]){2}([0-9A-Z]){2}([0-9A-Z]{3})?"); - } - - public String iban() { - List countryCodes = new ArrayList<>(countryCodeToBasicBankAccountNumberPattern.keySet()); - String randomCountryCode = countryCodes.get(faker.random().nextInt(countryCodes.size())); - return iban(randomCountryCode); + return sum; + } + + private static String calculateIbanChecksum(String countryCode, String basicBankAccountNumber) { + String basis = basicBankAccountNumber + countryCode + "00"; + + StringBuilder sb = new StringBuilder(); + char[] characters = basis.toLowerCase().toCharArray(); + for (char c : characters) { + if (Character.isLetter(c)) { + sb.append(String.valueOf((c - 'a') + 10)); + } else { + sb.append(c); + } } - public String iban(String countryCode) { - String basicBankAccountNumber = faker.regexify(countryCodeToBasicBankAccountNumberPattern.get(countryCode)); - String checkSum = calculateIbanChecksum(countryCode, basicBankAccountNumber); - return countryCode + checkSum + basicBankAccountNumber; - } - - private CreditCardType randomCreditCardType() { - return CreditCardType.values()[this.faker.random().nextInt(CreditCardType.values().length)]; - } - - private static int sum(String[] string) { - int sum = 0; - for (String s : string) { - if (!s.isEmpty()) { - sum += Integer.parseInt(s); - } - } - return sum; - } - - private static String calculateIbanChecksum(String countryCode, String basicBankAccountNumber) { - String basis = basicBankAccountNumber + countryCode + "00"; - - StringBuilder sb = new StringBuilder(); - char[] characters = basis.toLowerCase().toCharArray(); - for (char c : characters) { - if (Character.isLetter(c)) { - sb.append(String.valueOf((c - 'a') + 10)); - } else { - sb.append(c); - } - } - - int mod97 = new BigInteger(sb.toString()).mod(BigInteger.valueOf(97L)).intValue(); - return StringUtils.leftPad(String.valueOf(98 - mod97), 2, '0'); - } - - private static Map createCountryCodeToBasicBankAccountNumberPatternMap() { - // source: https://www.swift.com/standards/data-standards/iban - Map ibanFormats = new HashMap<>(); - ibanFormats.put("AL", "\\d{8}[0-9A-Za-z]{16}"); - ibanFormats.put("AD", "\\d{4}\\d{4}[0-9A-Za-z]{12}"); - ibanFormats.put("AT", "\\d{5}\\d{11}"); - ibanFormats.put("AZ", "[A-Z]{4}[0-9A-Za-z]{20}"); - ibanFormats.put("BH", "[A-Z]{4}[0-9A-Za-z]{14}"); - ibanFormats.put("BE", "\\d{3}\\d{7}\\d{2}"); - ibanFormats.put("BA", "\\d{3}\\d{3}\\d{8}\\d{2}"); - ibanFormats.put("BR", "\\d{8}\\d{5}\\d{10}[A-Z]{1}[0-9A-Za-z]{1}"); - ibanFormats.put("BG", "[A-Z]{4}\\d{4}\\d{2}[0-9A-Za-z]{8}"); - ibanFormats.put("CR", "\\d{3}\\d{14}"); - ibanFormats.put("HR", "\\d{7}\\d{10}"); - ibanFormats.put("CY", "\\d{3}\\d{5}[0-9A-Za-z]{16}"); - ibanFormats.put("DK", "\\d{4}\\d{9}\\d{1}"); - ibanFormats.put("DO", "[0-9A-Za-z]{4}\\d{20}"); - ibanFormats.put("EE", "\\d{2}\\d{2}\\d{11}\\d{1}"); - ibanFormats.put("FI", "\\d{6}\\d{7}\\d{1}"); - ibanFormats.put("FR", "\\d{5}\\d{5}[0-9A-Za-z]{11}\\d{2}"); - ibanFormats.put("GE", "[A-Z]{2}\\d{16}"); - ibanFormats.put("DE", "\\d{8}\\d{10}"); - ibanFormats.put("GI", "[A-Z]{4}[0-9A-Za-z]{15}"); - ibanFormats.put("GR", "\\d{3}\\d{4}[0-9A-Za-z]{16}"); - ibanFormats.put("GT", "[0-9A-Za-z]{4}[0-9A-Za-z]{20}"); - ibanFormats.put("HU", "\\d{3}\\d{4}\\d{1}\\d{15}\\d{1}"); - ibanFormats.put("IS", "\\d{4}\\d{2}\\d{6}\\d{10}"); - ibanFormats.put("IE", "[A-Z]{4}\\d{6}\\d{8}"); - ibanFormats.put("IL", "\\d{3}\\d{3}\\d{13}"); - ibanFormats.put("IT", "[A-Z]{1}\\d{5}\\d{5}[0-9A-Za-z]{12}"); - ibanFormats.put("JO", "[A-Z]{4}\\d{4}[0-9A-Za-z]{18}"); - ibanFormats.put("KZ", "\\d{3}[0-9A-Za-z]{13}"); - ibanFormats.put("XK", "\\d{4}\\d{10}\\d{2}"); - ibanFormats.put("KW", "[A-Z]{4}[0-9A-Za-z]{22}"); - ibanFormats.put("LV", "[A-Z]{4}[0-9A-Za-z]{13}"); - ibanFormats.put("LB", "\\d{4}[0-9A-Za-z]{20}"); - ibanFormats.put("LI", "\\d{5}[0-9A-Za-z]{12}"); - ibanFormats.put("LT", "\\d{5}\\d{11}"); - ibanFormats.put("LU", "\\d{3}[0-9A-Za-z]{13}"); - ibanFormats.put("MK", "\\d{3}[0-9A-Za-z]{10}\\d{2}"); - ibanFormats.put("MT", "[A-Z]{4}\\d{5}[0-9A-Za-z]{18}"); - ibanFormats.put("MR", "\\d{5}\\d{5}\\d{11}\\d{2}"); - ibanFormats.put("MU", "[A-Z]{4}\\d{2}\\d{2}\\d{12}\\d{3}[A-Z]{3}"); - ibanFormats.put("MD", "[0-9A-Za-z]{2}[0-9A-Za-z]{18}"); - ibanFormats.put("MC", "\\d{5}\\d{5}[0-9A-Za-z]{11}\\d{2}"); - ibanFormats.put("ME", "\\d{3}\\d{13}\\d{2}"); - ibanFormats.put("NL", "[A-Z]{4}\\d{10}"); - ibanFormats.put("NO", "\\d{4}\\d{6}\\d{1}"); - ibanFormats.put("PK", "[A-Z]{4}[0-9A-Za-z]{16}"); - ibanFormats.put("PS", "[A-Z]{4}[0-9A-Za-z]{21}"); - ibanFormats.put("PL", "\\d{8}\\d{16}"); - ibanFormats.put("PT", "\\d{4}\\d{4}\\d{11}\\d{2}"); - ibanFormats.put("QA", "[A-Z]{4}[0-9A-Za-z]{21}"); - ibanFormats.put("RO", "[A-Z]{4}[0-9A-Za-z]{16}"); - ibanFormats.put("LC", "[A-Z]{4}[0-9A-Za-z]{24}"); - ibanFormats.put("SM", "[A-Z]{1}\\d{5}\\d{5}[0-9A-Za-z]{12}"); - ibanFormats.put("ST", "\\d{8}\\d{11}\\d{2}"); - ibanFormats.put("SA", "\\d{2}[0-9A-Za-z]{18}"); - ibanFormats.put("RS", "\\d{3}\\d{13}\\d{2}"); - ibanFormats.put("SK", "\\d{4}\\d{6}\\d{10}"); - ibanFormats.put("SI", "\\d{5}\\d{8}\\d{2}"); - ibanFormats.put("ES", "\\d{4}\\d{4}\\d{1}\\d{1}\\d{10}"); - ibanFormats.put("SE", "\\d{3}\\d{16}\\d{1}"); - ibanFormats.put("CH", "\\d{5}[0-9A-Za-z]{12}"); - ibanFormats.put("TL", "\\d{3}\\d{14}\\d{2}"); - ibanFormats.put("TN", "\\d{2}\\d{3}\\d{13}\\d{2}"); - ibanFormats.put("TR", "\\d{5}\\d{1}[0-9A-Za-z]{16}"); - ibanFormats.put("UA", "\\d{6}[0-9A-Za-z]{19}"); - ibanFormats.put("AE", "\\d{3}\\d{16}"); - ibanFormats.put("GB", "[A-Z]{4}\\d{6}\\d{8}"); - ibanFormats.put("VG", "[A-Z]{4}\\d{16}"); - return ibanFormats; - } + int mod97 = new BigInteger(sb.toString()).mod(BigInteger.valueOf(97L)).intValue(); + return StringUtils.leftPad(String.valueOf(98 - mod97), 2, '0'); + } + + private static Map createCountryCodeToBasicBankAccountNumberPatternMap() { + // source: https://www.swift.com/standards/data-standards/iban + Map ibanFormats = new HashMap<>(); + ibanFormats.put("AL", "\\d{8}[0-9A-Za-z]{16}"); + ibanFormats.put("AD", "\\d{4}\\d{4}[0-9A-Za-z]{12}"); + ibanFormats.put("AT", "\\d{5}\\d{11}"); + ibanFormats.put("AZ", "[A-Z]{4}[0-9A-Za-z]{20}"); + ibanFormats.put("BH", "[A-Z]{4}[0-9A-Za-z]{14}"); + ibanFormats.put("BE", "\\d{3}\\d{7}\\d{2}"); + ibanFormats.put("BA", "\\d{3}\\d{3}\\d{8}\\d{2}"); + ibanFormats.put("BR", "\\d{8}\\d{5}\\d{10}[A-Z]{1}[0-9A-Za-z]{1}"); + ibanFormats.put("BG", "[A-Z]{4}\\d{4}\\d{2}[0-9A-Za-z]{8}"); + ibanFormats.put("CR", "\\d{3}\\d{14}"); + ibanFormats.put("HR", "\\d{7}\\d{10}"); + ibanFormats.put("CY", "\\d{3}\\d{5}[0-9A-Za-z]{16}"); + ibanFormats.put("DK", "\\d{4}\\d{9}\\d{1}"); + ibanFormats.put("DO", "[0-9A-Za-z]{4}\\d{20}"); + ibanFormats.put("EE", "\\d{2}\\d{2}\\d{11}\\d{1}"); + ibanFormats.put("FI", "\\d{6}\\d{7}\\d{1}"); + ibanFormats.put("FR", "\\d{5}\\d{5}[0-9A-Za-z]{11}\\d{2}"); + ibanFormats.put("GE", "[A-Z]{2}\\d{16}"); + ibanFormats.put("DE", "\\d{8}\\d{10}"); + ibanFormats.put("GI", "[A-Z]{4}[0-9A-Za-z]{15}"); + ibanFormats.put("GR", "\\d{3}\\d{4}[0-9A-Za-z]{16}"); + ibanFormats.put("GT", "[0-9A-Za-z]{4}[0-9A-Za-z]{20}"); + ibanFormats.put("HU", "\\d{3}\\d{4}\\d{1}\\d{15}\\d{1}"); + ibanFormats.put("IS", "\\d{4}\\d{2}\\d{6}\\d{10}"); + ibanFormats.put("IE", "[A-Z]{4}\\d{6}\\d{8}"); + ibanFormats.put("IL", "\\d{3}\\d{3}\\d{13}"); + ibanFormats.put("IT", "[A-Z]{1}\\d{5}\\d{5}[0-9A-Za-z]{12}"); + ibanFormats.put("JO", "[A-Z]{4}\\d{4}[0-9A-Za-z]{18}"); + ibanFormats.put("KZ", "\\d{3}[0-9A-Za-z]{13}"); + ibanFormats.put("XK", "\\d{4}\\d{10}\\d{2}"); + ibanFormats.put("KW", "[A-Z]{4}[0-9A-Za-z]{22}"); + ibanFormats.put("LV", "[A-Z]{4}[0-9A-Za-z]{13}"); + ibanFormats.put("LB", "\\d{4}[0-9A-Za-z]{20}"); + ibanFormats.put("LI", "\\d{5}[0-9A-Za-z]{12}"); + ibanFormats.put("LT", "\\d{5}\\d{11}"); + ibanFormats.put("LU", "\\d{3}[0-9A-Za-z]{13}"); + ibanFormats.put("MK", "\\d{3}[0-9A-Za-z]{10}\\d{2}"); + ibanFormats.put("MT", "[A-Z]{4}\\d{5}[0-9A-Za-z]{18}"); + ibanFormats.put("MR", "\\d{5}\\d{5}\\d{11}\\d{2}"); + ibanFormats.put("MU", "[A-Z]{4}\\d{2}\\d{2}\\d{12}\\d{3}[A-Z]{3}"); + ibanFormats.put("MD", "[0-9A-Za-z]{2}[0-9A-Za-z]{18}"); + ibanFormats.put("MC", "\\d{5}\\d{5}[0-9A-Za-z]{11}\\d{2}"); + ibanFormats.put("ME", "\\d{3}\\d{13}\\d{2}"); + ibanFormats.put("NL", "[A-Z]{4}\\d{10}"); + ibanFormats.put("NO", "\\d{4}\\d{6}\\d{1}"); + ibanFormats.put("PK", "[A-Z]{4}[0-9A-Za-z]{16}"); + ibanFormats.put("PS", "[A-Z]{4}[0-9A-Za-z]{21}"); + ibanFormats.put("PL", "\\d{8}\\d{16}"); + ibanFormats.put("PT", "\\d{4}\\d{4}\\d{11}\\d{2}"); + ibanFormats.put("QA", "[A-Z]{4}[0-9A-Za-z]{21}"); + ibanFormats.put("RO", "[A-Z]{4}[0-9A-Za-z]{16}"); + ibanFormats.put("LC", "[A-Z]{4}[0-9A-Za-z]{24}"); + ibanFormats.put("SM", "[A-Z]{1}\\d{5}\\d{5}[0-9A-Za-z]{12}"); + ibanFormats.put("ST", "\\d{8}\\d{11}\\d{2}"); + ibanFormats.put("SA", "\\d{2}[0-9A-Za-z]{18}"); + ibanFormats.put("RS", "\\d{3}\\d{13}\\d{2}"); + ibanFormats.put("SK", "\\d{4}\\d{6}\\d{10}"); + ibanFormats.put("SI", "\\d{5}\\d{8}\\d{2}"); + ibanFormats.put("ES", "\\d{4}\\d{4}\\d{1}\\d{1}\\d{10}"); + ibanFormats.put("SE", "\\d{3}\\d{16}\\d{1}"); + ibanFormats.put("CH", "\\d{5}[0-9A-Za-z]{12}"); + ibanFormats.put("TL", "\\d{3}\\d{14}\\d{2}"); + ibanFormats.put("TN", "\\d{2}\\d{3}\\d{13}\\d{2}"); + ibanFormats.put("TR", "\\d{5}\\d{1}[0-9A-Za-z]{16}"); + ibanFormats.put("UA", "\\d{6}[0-9A-Za-z]{19}"); + ibanFormats.put("AE", "\\d{3}\\d{16}"); + ibanFormats.put("GB", "[A-Z]{4}\\d{6}\\d{8}"); + ibanFormats.put("VG", "[A-Z]{4}\\d{16}"); + return ibanFormats; + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Food.java b/src/main/java/org/thejavaguy/javafaker/Food.java index 4937269..f413f7b 100644 --- a/src/main/java/org/thejavaguy/javafaker/Food.java +++ b/src/main/java/org/thejavaguy/javafaker/Food.java @@ -2,38 +2,39 @@ public class Food { - private final Faker faker; + private final Faker faker; - protected Food(Faker faker) { - this.faker = faker; - } + protected Food(Faker faker) { + this.faker = faker; + } - public String ingredient() { - return faker.fakeValuesService().resolve("food.ingredients", this, faker); - } + public String ingredient() { + return faker.fakeValuesService().resolve("food.ingredients", this, faker); + } - public String spice() { - return faker.fakeValuesService().resolve("food.spices", this, faker); - } + public String spice() { + return faker.fakeValuesService().resolve("food.spices", this, faker); + } - public String dish() { - return faker.fakeValuesService().resolve("food.dish", this, faker); - } + public String dish() { + return faker.fakeValuesService().resolve("food.dish", this, faker); + } - public String fruit() { - return faker.fakeValuesService().resolve("food.fruits", this, faker); - } + public String fruit() { + return faker.fakeValuesService().resolve("food.fruits", this, faker); + } - public String vegetable() { - return faker.fakeValuesService().resolve("food.vegetables", this, faker); - } + public String vegetable() { + return faker.fakeValuesService().resolve("food.vegetables", this, faker); + } - public String sushi() { - return faker.fakeValuesService().resolve("food.sushi", this, faker); - } + public String sushi() { + return faker.fakeValuesService().resolve("food.sushi", this, faker); + } - public String measurement() { - return faker.fakeValuesService().resolve("food.measurement_sizes", this, faker) + - " " + faker.fakeValuesService().resolve("food.measurements", this, faker); - } + public String measurement() { + return faker.fakeValuesService().resolve("food.measurement_sizes", this, faker) + + " " + + faker.fakeValuesService().resolve("food.measurements", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Friends.java b/src/main/java/org/thejavaguy/javafaker/Friends.java index 2c7890a..4938168 100644 --- a/src/main/java/org/thejavaguy/javafaker/Friends.java +++ b/src/main/java/org/thejavaguy/javafaker/Friends.java @@ -1,21 +1,21 @@ package org.thejavaguy.javafaker; public class Friends { - private final Faker faker; + private final Faker faker; - protected Friends(Faker faker) { - this.faker = faker; - } + protected Friends(Faker faker) { + this.faker = faker; + } - public String character() { - return faker.resolve("friends.characters"); - } + public String character() { + return faker.resolve("friends.characters"); + } - public String location() { - return faker.resolve("friends.locations"); - } + public String location() { + return faker.resolve("friends.locations"); + } - public String quote() { - return faker.resolve("friends.quotes"); - } + public String quote() { + return faker.resolve("friends.quotes"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/FunnyName.java b/src/main/java/org/thejavaguy/javafaker/FunnyName.java index 3ae7a0a..1c5cb9c 100644 --- a/src/main/java/org/thejavaguy/javafaker/FunnyName.java +++ b/src/main/java/org/thejavaguy/javafaker/FunnyName.java @@ -1,13 +1,13 @@ package org.thejavaguy.javafaker; public class FunnyName { - private final Faker faker; + private final Faker faker; - protected FunnyName(Faker faker) { - this.faker = faker; - } + protected FunnyName(Faker faker) { + this.faker = faker; + } - public String name() { - return faker.fakeValuesService().resolve("funny_name.name", this, faker); - } + public String name() { + return faker.fakeValuesService().resolve("funny_name.name", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/GameOfThrones.java b/src/main/java/org/thejavaguy/javafaker/GameOfThrones.java index 4db0bdd..db7da60 100644 --- a/src/main/java/org/thejavaguy/javafaker/GameOfThrones.java +++ b/src/main/java/org/thejavaguy/javafaker/GameOfThrones.java @@ -2,29 +2,29 @@ public class GameOfThrones { - private final Faker faker; + private final Faker faker; - protected GameOfThrones(Faker faker) { - this.faker = faker; - } + protected GameOfThrones(Faker faker) { + this.faker = faker; + } - public String character() { - return faker.resolve("game_of_thrones.characters"); - } + public String character() { + return faker.resolve("game_of_thrones.characters"); + } - public String house() { - return faker.resolve("game_of_thrones.houses"); - } + public String house() { + return faker.resolve("game_of_thrones.houses"); + } - public String city() { - return faker.resolve("game_of_thrones.cities"); - } + public String city() { + return faker.resolve("game_of_thrones.cities"); + } - public String dragon() { - return faker.resolve("game_of_thrones.dragons"); - } + public String dragon() { + return faker.resolve("game_of_thrones.dragons"); + } - public String quote() { - return faker.resolve("game_of_thrones.quotes"); - } + public String quote() { + return faker.resolve("game_of_thrones.quotes"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Gender.java b/src/main/java/org/thejavaguy/javafaker/Gender.java index 33b25f1..35ce261 100644 --- a/src/main/java/org/thejavaguy/javafaker/Gender.java +++ b/src/main/java/org/thejavaguy/javafaker/Gender.java @@ -1,41 +1,37 @@ package org.thejavaguy.javafaker; -/** - * This class is used to generate gender randomly. - * - */ - +/** This class is used to generate gender randomly. */ public class Gender { - private final Faker faker; + private final Faker faker; - protected Gender(Faker faker) { - this.faker = faker; - } + protected Gender(Faker faker) { + this.faker = faker; + } - /** - * This method returns a gender type - * - * @return a string of gender type - */ - public String types() { - return faker.fakeValuesService().fetchString("gender.types"); - } + /** + * This method returns a gender type + * + * @return a string of gender type + */ + public String types() { + return faker.fakeValuesService().fetchString("gender.types"); + } - /** - * This method returns a binary gender type - * - * @return a string of binary gender type - */ - public String binaryTypes() { - return faker.fakeValuesService().fetchString("gender.binary_types"); - } + /** + * This method returns a binary gender type + * + * @return a string of binary gender type + */ + public String binaryTypes() { + return faker.fakeValuesService().fetchString("gender.binary_types"); + } - /** - * This method returns a short binary gender type - * - * @return a string of short binary gender type - */ - public String shortBinaryTypes() { - return faker.fakeValuesService().fetchString("gender.short_binary_types"); - } + /** + * This method returns a short binary gender type + * + * @return a string of short binary gender type + */ + public String shortBinaryTypes() { + return faker.fakeValuesService().fetchString("gender.short_binary_types"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Hacker.java b/src/main/java/org/thejavaguy/javafaker/Hacker.java index e35d4ea..76e50b4 100644 --- a/src/main/java/org/thejavaguy/javafaker/Hacker.java +++ b/src/main/java/org/thejavaguy/javafaker/Hacker.java @@ -1,29 +1,29 @@ package org.thejavaguy.javafaker; public class Hacker { - private final Faker faker; + private final Faker faker; - protected Hacker(Faker faker) { - this.faker = faker; - } + protected Hacker(Faker faker) { + this.faker = faker; + } - public String abbreviation() { - return faker.fakeValuesService().resolve("hacker.abbreviation", this, faker); - } + public String abbreviation() { + return faker.fakeValuesService().resolve("hacker.abbreviation", this, faker); + } - public String adjective() { - return faker.fakeValuesService().resolve("hacker.adjective", this, faker); - } + public String adjective() { + return faker.fakeValuesService().resolve("hacker.adjective", this, faker); + } - public String noun() { - return faker.fakeValuesService().resolve("hacker.noun", this, faker); - } + public String noun() { + return faker.fakeValuesService().resolve("hacker.noun", this, faker); + } - public String verb() { - return faker.fakeValuesService().resolve("hacker.verb", this, faker); - } + public String verb() { + return faker.fakeValuesService().resolve("hacker.verb", this, faker); + } - public String ingverb() { - return faker.fakeValuesService().resolve("hacker.ingverb", this, faker); - } + public String ingverb() { + return faker.fakeValuesService().resolve("hacker.ingverb", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/HarryPotter.java b/src/main/java/org/thejavaguy/javafaker/HarryPotter.java index 44fe04e..27b99c9 100644 --- a/src/main/java/org/thejavaguy/javafaker/HarryPotter.java +++ b/src/main/java/org/thejavaguy/javafaker/HarryPotter.java @@ -1,33 +1,33 @@ package org.thejavaguy.javafaker; public class HarryPotter { - private final Faker faker; + private final Faker faker; - protected HarryPotter(final Faker faker) { - this.faker = faker; - } + protected HarryPotter(final Faker faker) { + this.faker = faker; + } - public String character() { - return faker.resolve("harry_potter.characters"); - } + public String character() { + return faker.resolve("harry_potter.characters"); + } - public String location() { - return faker.resolve("harry_potter.locations"); - } + public String location() { + return faker.resolve("harry_potter.locations"); + } - public String quote() { - return faker.resolve("harry_potter.quotes"); - } + public String quote() { + return faker.resolve("harry_potter.quotes"); + } - public String book() { - return faker.resolve("harry_potter.books"); - } + public String book() { + return faker.resolve("harry_potter.books"); + } - public String house() { - return faker.resolve("harry_potter.houses"); - } + public String house() { + return faker.resolve("harry_potter.houses"); + } - public String spell() { - return faker.resolve("harry_potter.spells"); - } + public String spell() { + return faker.resolve("harry_potter.spells"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Hipster.java b/src/main/java/org/thejavaguy/javafaker/Hipster.java index e3f4544..d80d02c 100644 --- a/src/main/java/org/thejavaguy/javafaker/Hipster.java +++ b/src/main/java/org/thejavaguy/javafaker/Hipster.java @@ -1,13 +1,13 @@ package org.thejavaguy.javafaker; public class Hipster { - private final Faker faker; + private final Faker faker; - protected Hipster(final Faker faker) { - this.faker = faker; - } + protected Hipster(final Faker faker) { + this.faker = faker; + } - public String word() { - return faker.resolve("hipster.words"); - } + public String word() { + return faker.resolve("hipster.words"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/HitchhikersGuideToTheGalaxy.java b/src/main/java/org/thejavaguy/javafaker/HitchhikersGuideToTheGalaxy.java index 16819ea..067d79e 100644 --- a/src/main/java/org/thejavaguy/javafaker/HitchhikersGuideToTheGalaxy.java +++ b/src/main/java/org/thejavaguy/javafaker/HitchhikersGuideToTheGalaxy.java @@ -1,37 +1,49 @@ package org.thejavaguy.javafaker; public class HitchhikersGuideToTheGalaxy { - private final Faker faker; - - protected HitchhikersGuideToTheGalaxy(Faker faker) { - this.faker = faker; - } - - public String character() { - return faker.fakeValuesService().resolve("hitchhikers_guide_to_the_galaxy.characters", this, faker); - } - - public String location() { - return faker.fakeValuesService().resolve("hitchhikers_guide_to_the_galaxy.locations", this, faker); - } - - public String marvinQuote() { - return faker.fakeValuesService().resolve("hitchhikers_guide_to_the_galaxy.marvin_quote", this, faker); - } - - public String planet() { - return faker.fakeValuesService().resolve("hitchhikers_guide_to_the_galaxy.planets", this, faker); - } - - public String quote() { - return faker.fakeValuesService().resolve("hitchhikers_guide_to_the_galaxy.quotes", this, faker); - } - - public String specie() { - return faker.fakeValuesService().resolve("hitchhikers_guide_to_the_galaxy.species", this, faker); - } - - public String starship() { - return faker.fakeValuesService().resolve("hitchhikers_guide_to_the_galaxy.starships", this, faker); - } + private final Faker faker; + + protected HitchhikersGuideToTheGalaxy(Faker faker) { + this.faker = faker; + } + + public String character() { + return faker + .fakeValuesService() + .resolve("hitchhikers_guide_to_the_galaxy.characters", this, faker); + } + + public String location() { + return faker + .fakeValuesService() + .resolve("hitchhikers_guide_to_the_galaxy.locations", this, faker); + } + + public String marvinQuote() { + return faker + .fakeValuesService() + .resolve("hitchhikers_guide_to_the_galaxy.marvin_quote", this, faker); + } + + public String planet() { + return faker + .fakeValuesService() + .resolve("hitchhikers_guide_to_the_galaxy.planets", this, faker); + } + + public String quote() { + return faker.fakeValuesService().resolve("hitchhikers_guide_to_the_galaxy.quotes", this, faker); + } + + public String specie() { + return faker + .fakeValuesService() + .resolve("hitchhikers_guide_to_the_galaxy.species", this, faker); + } + + public String starship() { + return faker + .fakeValuesService() + .resolve("hitchhikers_guide_to_the_galaxy.starships", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Hobbit.java b/src/main/java/org/thejavaguy/javafaker/Hobbit.java index 82f4ff7..db917e7 100644 --- a/src/main/java/org/thejavaguy/javafaker/Hobbit.java +++ b/src/main/java/org/thejavaguy/javafaker/Hobbit.java @@ -1,25 +1,25 @@ package org.thejavaguy.javafaker; public class Hobbit { - private final Faker faker; + private final Faker faker; - protected Hobbit(Faker faker) { - this.faker = faker; - } + protected Hobbit(Faker faker) { + this.faker = faker; + } - public String character() { - return faker.fakeValuesService().resolve("hobbit.character", this, faker); - } + public String character() { + return faker.fakeValuesService().resolve("hobbit.character", this, faker); + } - public String thorinsCompany() { - return faker.fakeValuesService().resolve("hobbit.thorins_company", this, faker); - } + public String thorinsCompany() { + return faker.fakeValuesService().resolve("hobbit.thorins_company", this, faker); + } - public String quote() { - return faker.fakeValuesService().resolve("hobbit.quote", this, faker); - } + public String quote() { + return faker.fakeValuesService().resolve("hobbit.quote", this, faker); + } - public String location() { - return faker.fakeValuesService().resolve("hobbit.location", this, faker); - } + public String location() { + return faker.fakeValuesService().resolve("hobbit.location", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/HowIMetYourMother.java b/src/main/java/org/thejavaguy/javafaker/HowIMetYourMother.java index f3d3425..edaf71b 100644 --- a/src/main/java/org/thejavaguy/javafaker/HowIMetYourMother.java +++ b/src/main/java/org/thejavaguy/javafaker/HowIMetYourMother.java @@ -1,25 +1,25 @@ package org.thejavaguy.javafaker; public class HowIMetYourMother { - private final Faker faker; + private final Faker faker; - protected HowIMetYourMother(Faker faker) { - this.faker = faker; - } + protected HowIMetYourMother(Faker faker) { + this.faker = faker; + } - public String character() { - return faker.fakeValuesService().resolve("how_i_met_your_mother.character", this, faker); - } + public String character() { + return faker.fakeValuesService().resolve("how_i_met_your_mother.character", this, faker); + } - public String catchPhrase() { - return faker.fakeValuesService().resolve("how_i_met_your_mother.catch_phrase", this, faker); - } + public String catchPhrase() { + return faker.fakeValuesService().resolve("how_i_met_your_mother.catch_phrase", this, faker); + } - public String highFive() { - return faker.fakeValuesService().resolve("how_i_met_your_mother.high_five", this, faker); - } + public String highFive() { + return faker.fakeValuesService().resolve("how_i_met_your_mother.high_five", this, faker); + } - public String quote() { - return faker.fakeValuesService().resolve("how_i_met_your_mother.quote", this, faker); - } + public String quote() { + return faker.fakeValuesService().resolve("how_i_met_your_mother.quote", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/IdNumber.java b/src/main/java/org/thejavaguy/javafaker/IdNumber.java index b153816..ad48fc0 100644 --- a/src/main/java/org/thejavaguy/javafaker/IdNumber.java +++ b/src/main/java/org/thejavaguy/javafaker/IdNumber.java @@ -4,38 +4,34 @@ import org.thejavaguy.javafaker.idnumbers.SvSEIdNumber; public class IdNumber { - private final Faker faker; - - protected IdNumber(Faker faker) { - this.faker = faker; - } - - public String valid() { - return faker.fakeValuesService().resolve("id_number.valid", this, faker); - } - - public String invalid() { - return faker.numerify(faker.fakeValuesService().resolve("id_number.invalid", this, faker)); - } - - public String ssnValid() { - EnIdNumber enIdNumber = new EnIdNumber(); - return enIdNumber.getValidSsn(faker); - } - - /** - * Specified as #{IDNumber.valid_sv_se_ssn} in sv-SE.yml - */ - public String validSvSeSsn() { - SvSEIdNumber svSEIdNumber = new SvSEIdNumber(); - return svSEIdNumber.getValidSsn(faker); - } - - /** - * Specified as #{IDNumber.invalid_sv_se_ssn} in sv-SE.yml - */ - public String invalidSvSeSsn() { - SvSEIdNumber svSEIdNumber = new SvSEIdNumber(); - return svSEIdNumber.getInvalidSsn(faker); - } + private final Faker faker; + + protected IdNumber(Faker faker) { + this.faker = faker; + } + + public String valid() { + return faker.fakeValuesService().resolve("id_number.valid", this, faker); + } + + public String invalid() { + return faker.numerify(faker.fakeValuesService().resolve("id_number.invalid", this, faker)); + } + + public String ssnValid() { + EnIdNumber enIdNumber = new EnIdNumber(); + return enIdNumber.getValidSsn(faker); + } + + /** Specified as #{IDNumber.valid_sv_se_ssn} in sv-SE.yml */ + public String validSvSeSsn() { + SvSEIdNumber svSEIdNumber = new SvSEIdNumber(); + return svSEIdNumber.getValidSsn(faker); + } + + /** Specified as #{IDNumber.invalid_sv_se_ssn} in sv-SE.yml */ + public String invalidSvSeSsn() { + SvSEIdNumber svSEIdNumber = new SvSEIdNumber(); + return svSEIdNumber.getInvalidSsn(faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Internet.java b/src/main/java/org/thejavaguy/javafaker/Internet.java index 5050964..87ff394 100644 --- a/src/main/java/org/thejavaguy/javafaker/Internet.java +++ b/src/main/java/org/thejavaguy/javafaker/Internet.java @@ -6,347 +6,367 @@ import java.util.Arrays; import java.util.List; import java.util.UUID; - import org.apache.commons.lang3.StringUtils; - import org.thejavaguy.javafaker.service.FakerIDN; import org.thejavaguy.javafaker.service.RandomService; public class Internet { - private final Faker faker; - - protected Internet(Faker faker) { - this.faker = faker; - } - - public String emailAddress() { - return emailAddress(faker.name().username()); - } - - public String emailAddress(String localPart) { - return emailAddress(localPart, FakerIDN.toASCII(faker.fakeValuesService().resolve("internet.free_email", this, faker))); - } - - public String safeEmailAddress() { - return safeEmailAddress(faker.name().username()); - } - - public String safeEmailAddress(String localPart) { - return emailAddress(localPart, FakerIDN.toASCII(faker.fakeValuesService().resolve("internet.safe_email", this, faker))); - } - - private String emailAddress(String localPart, String domain) { - return join(stripAccents(localPart), "@", domain); - } - - public String domainName() { - return domainWord() + "." + domainSuffix(); - } - - public String domainWord() { - return FakerIDN.toASCII(faker.name().lastName().toLowerCase().replaceAll("'", "")); - } - - public String domainSuffix() { - return faker.fakeValuesService().resolve("internet.domain_suffix", this, faker); - } - - public String url() { - return join( - "www", - ".", - FakerIDN.toASCII( - faker.name().firstName().toLowerCase().replaceAll("'", "") + - "-" + - domainWord() - ), - ".", - domainSuffix() - ); - } - - /** - * Generates a random avatar url based on a collection of profile pictures of real people. All this avatar have been - * authorized by its awesome users to be used on live websites (not just mockups). For more information, please - * visit: http://uifaces.com/authorized - * - * @return an url to a random avatar image. - * @see Authorized UI Faces - */ - public String avatar() { - return "https://s3.amazonaws.com/uifaces/faces/twitter/" + faker.fakeValuesService().resolve("internet.avatar", this, faker); - } - - /** - * Generates a random image url based on the lorempixel service. All the images provided by this service are released - * under the creative commons license (CC BY-SA). For more information, please visit: http://lorempixel.com/ - * - * @return an url to a random image. - * @see lorempixel - Placeholder Images for every case - */ - public String image() { - String[] dimension = StringUtils.split(faker.fakeValuesService().resolve("internet.image_dimension", this, faker), 'x'); - if (dimension.length == 0) return ""; - return image( - Integer.valueOf(StringUtils.trim(dimension[0])), Integer.valueOf(StringUtils.trim(dimension[1])), - faker.bool().bool(), null); - } - - /** - * Same as image() but allows client code to choose a few image characteristics - * - * @param width the image width - * @param height the image height - * @param gray true for gray image and false for color image - * @param text optional custom text on the selected picture - * @return an url to a random image with the given characteristics. - */ - public String image(Integer width, Integer height, Boolean gray, String text) { - return String.format("http://lorempixel.com/%s%s/%s/%s/%s", - gray ? "g/" : StringUtils.EMPTY, width, height, faker.fakeValuesService().resolve("internet.image_category", this, faker), - StringUtils.isEmpty(text) ? StringUtils.EMPTY : text); - } - - public String password() { - return password(8, 16); - } - - public String password(boolean includeDigit) { - return password(8, 16, false, false, includeDigit); - } - - public String password(int minimumLength, int maximumLength) { - return password(minimumLength, maximumLength, false); - } - - public String password(int minimumLength, int maximumLength, boolean includeUppercase) { - return password(minimumLength, maximumLength, includeUppercase, false); - } - - public String password(int minimumLength, int maximumLength, boolean includeUppercase, boolean includeSpecial) { - return password(minimumLength, maximumLength, includeUppercase, includeSpecial, true); - } - - public String password(int minimumLength, int maximumLength, boolean includeUppercase, boolean includeSpecial, boolean includeDigit) { - if (includeSpecial) { - char[] password = faker.lorem().characters(minimumLength, maximumLength, includeUppercase, includeDigit).toCharArray(); - char[] special = new char[]{'!', '@', '#', '$', '%', '^', '&', '*'}; - for (int i = 0; i < faker.random().nextInt(minimumLength); i++) { - password[faker.random().nextInt(password.length)] = special[faker.random().nextInt(special.length)]; - } - return new String(password); - } else { - return faker.lorem().characters(minimumLength, maximumLength, includeUppercase, includeDigit); - } - } - - /** - *

Returns a MAC address in the following format: 6-bytes in MM:MM:MM:SS:SS:SS format.

- * @return a correctly formatted MAC address - * @param prefix a prefix to put on the front of the address - */ - public String macAddress(String prefix) { - final String tmp = (prefix == null) ? "" : prefix; - final int prefixLength = tmp.trim().isEmpty() - ? 0 - : tmp.split(":").length; - - final StringBuilder out = new StringBuilder(tmp); - for (int i=0;i < 6 - prefixLength;i++) { - if (out.length() > 0) { - out.append(':'); - } - out.append(Integer.toHexString(faker.random().nextInt(16))); - out.append(Integer.toHexString(faker.random().nextInt(16))); - } - return out.toString(); - } - - /** - * @see Internet#macAddress(String) - */ - public String macAddress() { - return macAddress(""); - } - - /** - * returns an IPv4 address in dot separated octets. - * @return a correctly formatted IPv4 address. - */ - public String ipV4Address() { - return String.format("%d.%d.%d.%d", - faker.random().nextInt(254) + 2, - faker.random().nextInt(254) + 2, - faker.random().nextInt(254) + 2, - faker.random().nextInt(254) + 2); - } - - /** - * @return a valid private IPV4 address in dot notation - */ - public String privateIpV4Address() { - final Integer[] PRIVATE_FIRST_OCTET = {10,127,169,192,172}; - final Integer[] PRIVATE_SECOND_OCTET_172 = {16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31}; - - final RandomService r = faker.random(); - int first = random(PRIVATE_FIRST_OCTET), - second = r.nextInt(256), - third = r.nextInt(256), - fourth = r.nextInt(256); - - switch (first) { - case 172: - second = random(PRIVATE_SECOND_OCTET_172); - break; - case 192: - second = 168; - break; - case 169: - second = 254; - break; - } - return String.format("%d.%d.%d.%d", first, second, third, fourth); - } - - /** - * @return a valid public IPV4 address in dot notation - */ - public String publicIpV4Address() { - final RandomService r = faker.random(); - - final int[] PRIVATE_FIRST_OCTET = {10,127,169,192,172}; - - int first = r.nextInt(256), - second = r.nextInt(256), - third = r.nextInt(256), - fourth = r.nextInt(256); - - while (Arrays.binarySearch(PRIVATE_FIRST_OCTET, first) > 0) { - first = r.nextInt(256); - } - return String.format("%d.%d.%d.%d", first, second, third, fourth); - } - - /** - * @return a valid IPV4 CIDR - */ - public String ipV4Cidr() { - return new StringBuilder(ipV4Address()) - .append('/') - .append(faker.random().nextInt(31) + 1) - .toString(); - } - - /** - *

Returns an IPv6 address in hh:hh:hh:hh:hh:hh:hh:hh format.

- * @return a correctly formatted IPv6 address. - */ - public String ipV6Address() { - final StringBuilder tmp = new StringBuilder(); - for (int i=0;i < 8;i++) { - if (i > 0) { - tmp.append(":"); - } - tmp.append(Integer.toHexString(faker.random().nextInt(16))); - tmp.append(Integer.toHexString(faker.random().nextInt(16))); - tmp.append(Integer.toHexString(faker.random().nextInt(16))); - tmp.append(Integer.toHexString(faker.random().nextInt(16))); - } - return tmp.toString(); - } - - /** - * @return a valid IPV6 CIDR - */ - public String ipV6Cidr() { - return new StringBuilder(ipV6Address()) - .append('/') - .append(faker.random().nextInt(127) + 1) - .toString(); - } - - /** - * @return a slug using '_' as the word separator and two {@link Lorem} words as the values - */ - public String slug() { - return slug(faker.lorem().words(2), "_"); - } - - /** - * @param wordsOrNull if null, then 2 {@link Lorem} words - * @param glueOrNull if null, "_" - * @return a slug string combining wordsOrNull with glueOrNull (ex. x_y) - */ - public String slug(List wordsOrNull, String glueOrNull) { - final String glue = glueOrNull == null - ? "_" - : glueOrNull; - final List words = wordsOrNull == null - ? faker.lorem().words(2) - : wordsOrNull; - - final StringBuilder slug = new StringBuilder(); - for (int i = 0; i < words.size(); i++) { - if (i > 0) { - slug.append(glue); - } - slug.append(words.get(i)); - } - return slug.toString(); - } - - /** - * Returns a UUID (type 4) as String. - * @return A UUID as String. - */ - public String uuid() { - return UUID.randomUUID().toString(); - } - - private T random(T[] src) { - return src[faker.random().nextInt(src.length)]; - } - - public String userAgent(UserAgent userAgent) { - UserAgent agent = userAgent; - - if(agent == null) { - agent = UserAgent.any(); - } - - String userAgentKey = "internet.user_agent." + agent.toString(); - return faker.fakeValuesService().resolve(userAgentKey, this, faker); - } - - public String userAgentAny() { - return userAgent(null); - } - - public enum UserAgent { - AOL("aol"), - CHROME("chrome"), - FIREFOX("firefox"), - INTERNET_EXPLORER("internet_explorer"), - NETSCAPE("netscape"), - OPERA("opera"), - SAFARI("safari"); - - //Browser's name in corresponding yaml (internet.yml) file. - private String browserName; - - UserAgent(String browserName) { - this.browserName = browserName; - } - - private static UserAgent any() { - UserAgent[] agents = UserAgent.values(); - int randomIndex = (int)(Math.random() * agents.length); - return agents[randomIndex]; - } - - @Override - public String toString() { - return browserName; - } - } + private final Faker faker; + + protected Internet(Faker faker) { + this.faker = faker; + } + + public String emailAddress() { + return emailAddress(faker.name().username()); + } + + public String emailAddress(String localPart) { + return emailAddress( + localPart, + FakerIDN.toASCII(faker.fakeValuesService().resolve("internet.free_email", this, faker))); + } + + public String safeEmailAddress() { + return safeEmailAddress(faker.name().username()); + } + + public String safeEmailAddress(String localPart) { + return emailAddress( + localPart, + FakerIDN.toASCII(faker.fakeValuesService().resolve("internet.safe_email", this, faker))); + } + + private String emailAddress(String localPart, String domain) { + return join(stripAccents(localPart), "@", domain); + } + + public String domainName() { + return domainWord() + "." + domainSuffix(); + } + + public String domainWord() { + return FakerIDN.toASCII(faker.name().lastName().toLowerCase().replaceAll("'", "")); + } + + public String domainSuffix() { + return faker.fakeValuesService().resolve("internet.domain_suffix", this, faker); + } + + public String url() { + return join( + "www", + ".", + FakerIDN.toASCII( + faker.name().firstName().toLowerCase().replaceAll("'", "") + "-" + domainWord()), + ".", + domainSuffix()); + } + + /** + * Generates a random avatar url based on a collection of profile pictures of real people. All + * this avatar have been authorized by its awesome users to be used on live websites (not just + * mockups). For more information, please visit: http://uifaces.com/authorized + * + * @return an url to a random avatar image. + * @see Authorized UI Faces + */ + public String avatar() { + return "https://s3.amazonaws.com/uifaces/faces/twitter/" + + faker.fakeValuesService().resolve("internet.avatar", this, faker); + } + + /** + * Generates a random image url based on the lorempixel service. All the images provided by this + * service are released under the creative commons license (CC BY-SA). For more information, + * please visit: http://lorempixel.com/ + * + * @return an url to a random image. + * @see lorempixel - Placeholder Images for every case + */ + public String image() { + String[] dimension = + StringUtils.split( + faker.fakeValuesService().resolve("internet.image_dimension", this, faker), 'x'); + if (dimension.length == 0) return ""; + return image( + Integer.valueOf(StringUtils.trim(dimension[0])), + Integer.valueOf(StringUtils.trim(dimension[1])), + faker.bool().bool(), + null); + } + + /** + * Same as image() but allows client code to choose a few image characteristics + * + * @param width the image width + * @param height the image height + * @param gray true for gray image and false for color image + * @param text optional custom text on the selected picture + * @return an url to a random image with the given characteristics. + */ + public String image(Integer width, Integer height, Boolean gray, String text) { + return String.format( + "http://lorempixel.com/%s%s/%s/%s/%s", + gray ? "g/" : StringUtils.EMPTY, + width, + height, + faker.fakeValuesService().resolve("internet.image_category", this, faker), + StringUtils.isEmpty(text) ? StringUtils.EMPTY : text); + } + + public String password() { + return password(8, 16); + } + + public String password(boolean includeDigit) { + return password(8, 16, false, false, includeDigit); + } + + public String password(int minimumLength, int maximumLength) { + return password(minimumLength, maximumLength, false); + } + + public String password(int minimumLength, int maximumLength, boolean includeUppercase) { + return password(minimumLength, maximumLength, includeUppercase, false); + } + + public String password( + int minimumLength, int maximumLength, boolean includeUppercase, boolean includeSpecial) { + return password(minimumLength, maximumLength, includeUppercase, includeSpecial, true); + } + + public String password( + int minimumLength, + int maximumLength, + boolean includeUppercase, + boolean includeSpecial, + boolean includeDigit) { + if (includeSpecial) { + char[] password = + faker + .lorem() + .characters(minimumLength, maximumLength, includeUppercase, includeDigit) + .toCharArray(); + char[] special = new char[] {'!', '@', '#', '$', '%', '^', '&', '*'}; + for (int i = 0; i < faker.random().nextInt(minimumLength); i++) { + password[faker.random().nextInt(password.length)] = + special[faker.random().nextInt(special.length)]; + } + return new String(password); + } else { + return faker.lorem().characters(minimumLength, maximumLength, includeUppercase, includeDigit); + } + } + + /** + * Returns a MAC address in the following format: 6-bytes in MM:MM:MM:SS:SS:SS format. + * + * @return a correctly formatted MAC address + * @param prefix a prefix to put on the front of the address + */ + public String macAddress(String prefix) { + final String tmp = (prefix == null) ? "" : prefix; + final int prefixLength = tmp.trim().isEmpty() ? 0 : tmp.split(":").length; + + final StringBuilder out = new StringBuilder(tmp); + for (int i = 0; i < 6 - prefixLength; i++) { + if (out.length() > 0) { + out.append(':'); + } + out.append(Integer.toHexString(faker.random().nextInt(16))); + out.append(Integer.toHexString(faker.random().nextInt(16))); + } + return out.toString(); + } + + /** + * @see Internet#macAddress(String) + */ + public String macAddress() { + return macAddress(""); + } + + /** + * returns an IPv4 address in dot separated octets. + * + * @return a correctly formatted IPv4 address. + */ + public String ipV4Address() { + return String.format( + "%d.%d.%d.%d", + faker.random().nextInt(254) + 2, + faker.random().nextInt(254) + 2, + faker.random().nextInt(254) + 2, + faker.random().nextInt(254) + 2); + } + + /** + * @return a valid private IPV4 address in dot notation + */ + public String privateIpV4Address() { + final Integer[] PRIVATE_FIRST_OCTET = {10, 127, 169, 192, 172}; + final Integer[] PRIVATE_SECOND_OCTET_172 = { + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 + }; + + final RandomService r = faker.random(); + int first = random(PRIVATE_FIRST_OCTET), + second = r.nextInt(256), + third = r.nextInt(256), + fourth = r.nextInt(256); + + switch (first) { + case 172: + second = random(PRIVATE_SECOND_OCTET_172); + break; + case 192: + second = 168; + break; + case 169: + second = 254; + break; + } + return String.format("%d.%d.%d.%d", first, second, third, fourth); + } + + /** + * @return a valid public IPV4 address in dot notation + */ + public String publicIpV4Address() { + final RandomService r = faker.random(); + + final int[] PRIVATE_FIRST_OCTET = {10, 127, 169, 192, 172}; + + int first = r.nextInt(256), + second = r.nextInt(256), + third = r.nextInt(256), + fourth = r.nextInt(256); + + while (Arrays.binarySearch(PRIVATE_FIRST_OCTET, first) > 0) { + first = r.nextInt(256); + } + return String.format("%d.%d.%d.%d", first, second, third, fourth); + } + + /** + * @return a valid IPV4 CIDR + */ + public String ipV4Cidr() { + return new StringBuilder(ipV4Address()) + .append('/') + .append(faker.random().nextInt(31) + 1) + .toString(); + } + + /** + * Returns an IPv6 address in hh:hh:hh:hh:hh:hh:hh:hh format. + * + * @return a correctly formatted IPv6 address. + */ + public String ipV6Address() { + final StringBuilder tmp = new StringBuilder(); + for (int i = 0; i < 8; i++) { + if (i > 0) { + tmp.append(":"); + } + tmp.append(Integer.toHexString(faker.random().nextInt(16))); + tmp.append(Integer.toHexString(faker.random().nextInt(16))); + tmp.append(Integer.toHexString(faker.random().nextInt(16))); + tmp.append(Integer.toHexString(faker.random().nextInt(16))); + } + return tmp.toString(); + } + + /** + * @return a valid IPV6 CIDR + */ + public String ipV6Cidr() { + return new StringBuilder(ipV6Address()) + .append('/') + .append(faker.random().nextInt(127) + 1) + .toString(); + } + + /** + * @return a slug using '_' as the word separator and two {@link Lorem} words as the values + */ + public String slug() { + return slug(faker.lorem().words(2), "_"); + } + + /** + * @param wordsOrNull if null, then 2 {@link Lorem} words + * @param glueOrNull if null, "_" + * @return a slug string combining wordsOrNull with glueOrNull (ex. x_y) + */ + public String slug(List wordsOrNull, String glueOrNull) { + final String glue = glueOrNull == null ? "_" : glueOrNull; + final List words = wordsOrNull == null ? faker.lorem().words(2) : wordsOrNull; + + final StringBuilder slug = new StringBuilder(); + for (int i = 0; i < words.size(); i++) { + if (i > 0) { + slug.append(glue); + } + slug.append(words.get(i)); + } + return slug.toString(); + } + + /** + * Returns a UUID (type 4) as String. + * + * @return A UUID as String. + */ + public String uuid() { + return UUID.randomUUID().toString(); + } + + private T random(T[] src) { + return src[faker.random().nextInt(src.length)]; + } + + public String userAgent(UserAgent userAgent) { + UserAgent agent = userAgent; + + if (agent == null) { + agent = UserAgent.any(); + } + + String userAgentKey = "internet.user_agent." + agent.toString(); + return faker.fakeValuesService().resolve(userAgentKey, this, faker); + } + + public String userAgentAny() { + return userAgent(null); + } + + public enum UserAgent { + AOL("aol"), + CHROME("chrome"), + FIREFOX("firefox"), + INTERNET_EXPLORER("internet_explorer"), + NETSCAPE("netscape"), + OPERA("opera"), + SAFARI("safari"); + + // Browser's name in corresponding yaml (internet.yml) file. + private String browserName; + + UserAgent(String browserName) { + this.browserName = browserName; + } + + private static UserAgent any() { + UserAgent[] agents = UserAgent.values(); + int randomIndex = (int) (Math.random() * agents.length); + return agents[randomIndex]; + } + + @Override + public String toString() { + return browserName; + } + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Job.java b/src/main/java/org/thejavaguy/javafaker/Job.java index 5d8a074..66f17a8 100644 --- a/src/main/java/org/thejavaguy/javafaker/Job.java +++ b/src/main/java/org/thejavaguy/javafaker/Job.java @@ -2,29 +2,29 @@ public class Job { - private final Faker faker; + private final Faker faker; - public Job(final Faker faker) { - this.faker = faker; - } + public Job(final Faker faker) { + this.faker = faker; + } - public String field() { - return faker.fakeValuesService().resolve("job.field", this, faker); - } + public String field() { + return faker.fakeValuesService().resolve("job.field", this, faker); + } - public String seniority() { - return faker.fakeValuesService().resolve("job.seniority", this, faker); - } + public String seniority() { + return faker.fakeValuesService().resolve("job.seniority", this, faker); + } - public String position() { - return faker.fakeValuesService().resolve("job.position", this, faker); - } + public String position() { + return faker.fakeValuesService().resolve("job.position", this, faker); + } - public String keySkills() { - return faker.fakeValuesService().resolve("job.key_skills", this, faker); - } + public String keySkills() { + return faker.fakeValuesService().resolve("job.key_skills", this, faker); + } - public String title() { - return faker.fakeValuesService().resolve("job.title", this, faker); - } + public String title() { + return faker.fakeValuesService().resolve("job.title", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Kaamelott.java b/src/main/java/org/thejavaguy/javafaker/Kaamelott.java index 127501e..393cd02 100644 --- a/src/main/java/org/thejavaguy/javafaker/Kaamelott.java +++ b/src/main/java/org/thejavaguy/javafaker/Kaamelott.java @@ -1,17 +1,17 @@ package org.thejavaguy.javafaker; public class Kaamelott { - private final Faker faker; + private final Faker faker; - protected Kaamelott(Faker faker) { - this.faker = faker; - } + protected Kaamelott(Faker faker) { + this.faker = faker; + } - public String character() { - return faker.fakeValuesService().resolve("kaamelott.characters", this, faker); - } + public String character() { + return faker.fakeValuesService().resolve("kaamelott.characters", this, faker); + } - public String quote() { - return faker.fakeValuesService().resolve("kaamelott.quotes", this, faker); - } + public String quote() { + return faker.fakeValuesService().resolve("kaamelott.quotes", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/LeagueOfLegends.java b/src/main/java/org/thejavaguy/javafaker/LeagueOfLegends.java index ef0df4f..bd7fac1 100644 --- a/src/main/java/org/thejavaguy/javafaker/LeagueOfLegends.java +++ b/src/main/java/org/thejavaguy/javafaker/LeagueOfLegends.java @@ -1,33 +1,33 @@ package org.thejavaguy.javafaker; public class LeagueOfLegends { - private final Faker faker; + private final Faker faker; - protected LeagueOfLegends(Faker faker) { - this.faker = faker; - } + protected LeagueOfLegends(Faker faker) { + this.faker = faker; + } - public String champion() { - return faker.fakeValuesService().resolve("games.league_of_legends.champion", this, faker); - } + public String champion() { + return faker.fakeValuesService().resolve("games.league_of_legends.champion", this, faker); + } - public String location() { - return faker.fakeValuesService().resolve("games.league_of_legends.location", this, faker); - } + public String location() { + return faker.fakeValuesService().resolve("games.league_of_legends.location", this, faker); + } - public String quote() { - return faker.fakeValuesService().resolve("games.league_of_legends.quote", this, faker); - } + public String quote() { + return faker.fakeValuesService().resolve("games.league_of_legends.quote", this, faker); + } - public String summonerSpell() { - return faker.fakeValuesService().resolve("games.league_of_legends.summoner_spell", this, faker); - } + public String summonerSpell() { + return faker.fakeValuesService().resolve("games.league_of_legends.summoner_spell", this, faker); + } - public String masteries() { - return faker.fakeValuesService().resolve("games.league_of_legends.masteries", this, faker); - } + public String masteries() { + return faker.fakeValuesService().resolve("games.league_of_legends.masteries", this, faker); + } - public String rank() { - return faker.fakeValuesService().resolve("games.league_of_legends.rank", this, faker); - } + public String rank() { + return faker.fakeValuesService().resolve("games.league_of_legends.rank", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Lebowski.java b/src/main/java/org/thejavaguy/javafaker/Lebowski.java index 5ae0bec..d3f2bba 100644 --- a/src/main/java/org/thejavaguy/javafaker/Lebowski.java +++ b/src/main/java/org/thejavaguy/javafaker/Lebowski.java @@ -1,21 +1,21 @@ package org.thejavaguy.javafaker; public class Lebowski { - private final Faker faker; + private final Faker faker; - public Lebowski(final Faker faker) { - this.faker = faker; - } + public Lebowski(final Faker faker) { + this.faker = faker; + } - public String actor() { - return faker.fakeValuesService().resolve("lebowski.actors", this, faker); - } + public String actor() { + return faker.fakeValuesService().resolve("lebowski.actors", this, faker); + } - public String character() { - return faker.fakeValuesService().resolve("lebowski.characters", this, faker); - } + public String character() { + return faker.fakeValuesService().resolve("lebowski.characters", this, faker); + } - public String quote() { - return faker.fakeValuesService().resolve("lebowski.quotes", this, faker); - } + public String quote() { + return faker.fakeValuesService().resolve("lebowski.quotes", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/LordOfTheRings.java b/src/main/java/org/thejavaguy/javafaker/LordOfTheRings.java index c95ccb9..5a6d03d 100644 --- a/src/main/java/org/thejavaguy/javafaker/LordOfTheRings.java +++ b/src/main/java/org/thejavaguy/javafaker/LordOfTheRings.java @@ -1,17 +1,17 @@ package org.thejavaguy.javafaker; public class LordOfTheRings { - private final Faker faker; + private final Faker faker; - protected LordOfTheRings(final Faker faker) { - this.faker = faker; - } + protected LordOfTheRings(final Faker faker) { + this.faker = faker; + } - public String character() { - return faker.resolve("lord_of_the_rings.characters"); - } + public String character() { + return faker.resolve("lord_of_the_rings.characters"); + } - public String location() { - return faker.resolve("lord_of_the_rings.locations"); - } + public String location() { + return faker.resolve("lord_of_the_rings.locations"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Lorem.java b/src/main/java/org/thejavaguy/javafaker/Lorem.java index bbbc8a6..76f3b37 100644 --- a/src/main/java/org/thejavaguy/javafaker/Lorem.java +++ b/src/main/java/org/thejavaguy/javafaker/Lorem.java @@ -5,172 +5,179 @@ import java.util.ArrayList; import java.util.List; - import org.apache.commons.lang3.StringUtils; public class Lorem { - private final Faker faker; - - protected Lorem(Faker faker) { - this.faker = faker; - } - - public char character() { - return character(false); - } - - public char character(boolean includeUppercase) { - return characters(1, includeUppercase).charAt(0); - } - - public String characters() { - return characters(255, false); - } - - public String characters(boolean includeUppercase) { - return characters(255, includeUppercase); - } - - public String characters(int minimumLength, int maximumLength) { - return characters(faker.random().nextInt(maximumLength - minimumLength) + minimumLength, false); - } - - public String characters(int minimumLength, int maximumLength, boolean includeUppercase) { - return characters(faker.random().nextInt(maximumLength - minimumLength) + minimumLength, includeUppercase); - } - - public String characters(int minimumLength, int maximumLength, boolean includeUppercase, boolean includeDigit) { - return characters(faker.random().nextInt(maximumLength - minimumLength) + minimumLength, includeUppercase, includeDigit); - } - - public String characters(int fixedNumberOfCharacters) { - return characters(fixedNumberOfCharacters, false); - } - - public String characters(int fixedNumberOfCharacters, boolean includeUppercase) { - return characters(fixedNumberOfCharacters, includeUppercase, true); - } - - public String characters(int fixedNumberOfCharacters, boolean includeUppercase, boolean includeDigit) { - if (fixedNumberOfCharacters < 1) { - return ""; - } - char[] buffer = new char[fixedNumberOfCharacters]; - for (int i = 0; i < buffer.length; i++) { - char randomCharacter; - - if (includeDigit) { - randomCharacter = characters[faker.random().nextInt(characters.length)]; - } else { - randomCharacter = letters[faker.random().nextInt(letters.length)]; - } - - if (includeUppercase && faker.bool().bool()) { - randomCharacter = Character.toUpperCase(randomCharacter); - } - buffer[i] = randomCharacter; - } - return new String(buffer); - } - - public List words(int num) { - List returnList = new ArrayList<>(); - for (int i = 0; i < num; i++) { - returnList.add(word()); - } - return returnList; - } - - public List words() { - return words(3); - } - - public String word() { - return faker.fakeValuesService().resolve("lorem.words", this, faker); - } - - /** - * Create a sentence with a random number of words within the range 4..10. - * @return a random sentence - */ - public String sentence() { - return sentence(3); - } - - /** - * Create a sentence with a random number of words within the range (wordCount+1)..(wordCount+6). - * @param wordCount - * @return a random sentence - */ - public String sentence(int wordCount) { - return sentence(wordCount, 6); - } - - /** - * Create a sentence with a random number of words within the range (wordCount+1)..(wordCount+randomWordsToAdd).

- * - * Set {@code randomWordsToAdd} to 0 to generate sentences with a fixed number of words. - * @param wordCount - * @param randomWordsToAdd - * @return a random sentence - */ - public String sentence(int wordCount, int randomWordsToAdd) { - int numberOfWordsToAdd = randomWordsToAdd == 0 ? 0 : faker.random().nextInt(randomWordsToAdd); - return capitalize(join(words(wordCount + numberOfWordsToAdd), " ") + "."); - } - - public List sentences(int sentenceCount) { - List sentences = new ArrayList<>(sentenceCount); - for (int i = 0; i < sentenceCount; i++) { - sentences.add(sentence()); - } - return sentences; - } - - public String paragraph(int sentenceCount) { - return join(sentences(sentenceCount + faker.random().nextInt(3)), " "); - } - - public String paragraph() { - return paragraph(3); - } - - public List paragraphs(int paragraphCount) { - List paragraphs = new ArrayList<>(paragraphCount); - for (int i = 0; i < paragraphCount; i++) { - paragraphs.add(paragraph()); - } - return paragraphs; - } - - /** - * Create a string with a fixed size. Can be useful for testing - * validator based on length string for example - * - * @param numberOfLetters size of the expected String - * @return a string with a fixed size - */ - public String fixedString(int numberOfLetters) { - StringBuilder builder = new StringBuilder(); - while (builder.length() < numberOfLetters) { - builder.append(sentence()); - } - return StringUtils.substring(builder.toString(), 0, numberOfLetters); - } - - static { - StringBuilder builder = new StringBuilder(36); - for (char character = 'a'; character <= 'z'; character++) { - builder.append(character); - } - letters = builder.toString().toCharArray(); - for (char number = '0'; number <= '9'; number++) { - builder.append(number); - } - characters = builder.toString().toCharArray(); - } - - private static final char[] letters; - private static final char[] characters; - + private final Faker faker; + + protected Lorem(Faker faker) { + this.faker = faker; + } + + public char character() { + return character(false); + } + + public char character(boolean includeUppercase) { + return characters(1, includeUppercase).charAt(0); + } + + public String characters() { + return characters(255, false); + } + + public String characters(boolean includeUppercase) { + return characters(255, includeUppercase); + } + + public String characters(int minimumLength, int maximumLength) { + return characters(faker.random().nextInt(maximumLength - minimumLength) + minimumLength, false); + } + + public String characters(int minimumLength, int maximumLength, boolean includeUppercase) { + return characters( + faker.random().nextInt(maximumLength - minimumLength) + minimumLength, includeUppercase); + } + + public String characters( + int minimumLength, int maximumLength, boolean includeUppercase, boolean includeDigit) { + return characters( + faker.random().nextInt(maximumLength - minimumLength) + minimumLength, + includeUppercase, + includeDigit); + } + + public String characters(int fixedNumberOfCharacters) { + return characters(fixedNumberOfCharacters, false); + } + + public String characters(int fixedNumberOfCharacters, boolean includeUppercase) { + return characters(fixedNumberOfCharacters, includeUppercase, true); + } + + public String characters( + int fixedNumberOfCharacters, boolean includeUppercase, boolean includeDigit) { + if (fixedNumberOfCharacters < 1) { + return ""; + } + char[] buffer = new char[fixedNumberOfCharacters]; + for (int i = 0; i < buffer.length; i++) { + char randomCharacter; + + if (includeDigit) { + randomCharacter = characters[faker.random().nextInt(characters.length)]; + } else { + randomCharacter = letters[faker.random().nextInt(letters.length)]; + } + + if (includeUppercase && faker.bool().bool()) { + randomCharacter = Character.toUpperCase(randomCharacter); + } + buffer[i] = randomCharacter; + } + return new String(buffer); + } + + public List words(int num) { + List returnList = new ArrayList<>(); + for (int i = 0; i < num; i++) { + returnList.add(word()); + } + return returnList; + } + + public List words() { + return words(3); + } + + public String word() { + return faker.fakeValuesService().resolve("lorem.words", this, faker); + } + + /** + * Create a sentence with a random number of words within the range 4..10. + * + * @return a random sentence + */ + public String sentence() { + return sentence(3); + } + + /** + * Create a sentence with a random number of words within the range (wordCount+1)..(wordCount+6). + * + * @param wordCount + * @return a random sentence + */ + public String sentence(int wordCount) { + return sentence(wordCount, 6); + } + + /** + * Create a sentence with a random number of words within the range + * (wordCount+1)..(wordCount+randomWordsToAdd). Set {@code randomWordsToAdd} to 0 to generate + * sentences with a fixed number of words. + * + * @param wordCount + * @param randomWordsToAdd + * @return a random sentence + */ + public String sentence(int wordCount, int randomWordsToAdd) { + int numberOfWordsToAdd = randomWordsToAdd == 0 ? 0 : faker.random().nextInt(randomWordsToAdd); + return capitalize(join(words(wordCount + numberOfWordsToAdd), " ") + "."); + } + + public List sentences(int sentenceCount) { + List sentences = new ArrayList<>(sentenceCount); + for (int i = 0; i < sentenceCount; i++) { + sentences.add(sentence()); + } + return sentences; + } + + public String paragraph(int sentenceCount) { + return join(sentences(sentenceCount + faker.random().nextInt(3)), " "); + } + + public String paragraph() { + return paragraph(3); + } + + public List paragraphs(int paragraphCount) { + List paragraphs = new ArrayList<>(paragraphCount); + for (int i = 0; i < paragraphCount; i++) { + paragraphs.add(paragraph()); + } + return paragraphs; + } + + /** + * Create a string with a fixed size. Can be useful for testing validator based on length string + * for example + * + * @param numberOfLetters size of the expected String + * @return a string with a fixed size + */ + public String fixedString(int numberOfLetters) { + StringBuilder builder = new StringBuilder(); + while (builder.length() < numberOfLetters) { + builder.append(sentence()); + } + return StringUtils.substring(builder.toString(), 0, numberOfLetters); + } + + static { + StringBuilder builder = new StringBuilder(36); + for (char character = 'a'; character <= 'z'; character++) { + builder.append(character); + } + letters = builder.toString().toCharArray(); + for (char number = '0'; number <= '9'; number++) { + builder.append(number); + } + characters = builder.toString().toCharArray(); + } + + private static final char[] letters; + private static final char[] characters; } diff --git a/src/main/java/org/thejavaguy/javafaker/Matz.java b/src/main/java/org/thejavaguy/javafaker/Matz.java index 38c53f9..28f39c9 100644 --- a/src/main/java/org/thejavaguy/javafaker/Matz.java +++ b/src/main/java/org/thejavaguy/javafaker/Matz.java @@ -1,13 +1,13 @@ package org.thejavaguy.javafaker; public class Matz { - private final Faker faker; + private final Faker faker; - protected Matz(final Faker faker) { - this.faker = faker; - } + protected Matz(final Faker faker) { + this.faker = faker; + } - public String quote() { - return faker.resolve("matz.quotes"); - } + public String quote() { + return faker.resolve("matz.quotes"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Medical.java b/src/main/java/org/thejavaguy/javafaker/Medical.java index 0f4fa98..dd09e2a 100644 --- a/src/main/java/org/thejavaguy/javafaker/Medical.java +++ b/src/main/java/org/thejavaguy/javafaker/Medical.java @@ -2,25 +2,25 @@ public class Medical { - private final Faker faker; + private final Faker faker; - protected Medical(Faker faker) { - this.faker = faker; - } + protected Medical(Faker faker) { + this.faker = faker; + } - public String medicineName() { - return faker.fakeValuesService().resolve("medical.medicine_name", this, faker); - } + public String medicineName() { + return faker.fakeValuesService().resolve("medical.medicine_name", this, faker); + } - public String diseaseName() { - return faker.fakeValuesService().resolve("medical.disease_name", this, faker); - } + public String diseaseName() { + return faker.fakeValuesService().resolve("medical.disease_name", this, faker); + } - public String hospitalName() { - return faker.fakeValuesService().resolve("medical.hospital_name", this, faker); - } + public String hospitalName() { + return faker.fakeValuesService().resolve("medical.hospital_name", this, faker); + } - public String symptoms() { - return faker.fakeValuesService().resolve("medical.symptoms", this, faker); - } + public String symptoms() { + return faker.fakeValuesService().resolve("medical.symptoms", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Mountain.java b/src/main/java/org/thejavaguy/javafaker/Mountain.java index c4875db..1a04db9 100644 --- a/src/main/java/org/thejavaguy/javafaker/Mountain.java +++ b/src/main/java/org/thejavaguy/javafaker/Mountain.java @@ -1,17 +1,17 @@ package org.thejavaguy.javafaker; public class Mountain { - private final Faker faker; + private final Faker faker; - protected Mountain(Faker faker) { - this.faker = faker; - } + protected Mountain(Faker faker) { + this.faker = faker; + } - public String name() { - return faker.fakeValuesService().resolve("mountain.name", this, faker); - } + public String name() { + return faker.fakeValuesService().resolve("mountain.name", this, faker); + } - public String range() { - return faker.fakeValuesService().resolve("mountain.range", this, faker); - } + public String range() { + return faker.fakeValuesService().resolve("mountain.range", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Music.java b/src/main/java/org/thejavaguy/javafaker/Music.java index 956fa03..021a532 100644 --- a/src/main/java/org/thejavaguy/javafaker/Music.java +++ b/src/main/java/org/thejavaguy/javafaker/Music.java @@ -2,29 +2,30 @@ public class Music { - private static final String[] KEYS = new String[] { "C", "D", "E", "F", "G", "A", "B" }; - private static final String[] KEY_VARIANTS = new String[] { "b", "#", "" }; - private static final String[] CHORD_TYPES = new String[] { "", "maj", "6", "maj7", "m", "m7", "-7", "7", "dom7", "dim", "dim7", "m7b5"}; + private static final String[] KEYS = new String[] {"C", "D", "E", "F", "G", "A", "B"}; + private static final String[] KEY_VARIANTS = new String[] {"b", "#", ""}; + private static final String[] CHORD_TYPES = + new String[] {"", "maj", "6", "maj7", "m", "m7", "-7", "7", "dom7", "dim", "dim7", "m7b5"}; - private final Faker faker; + private final Faker faker; - protected Music(Faker faker) { - this.faker = faker; - } + protected Music(Faker faker) { + this.faker = faker; + } - public String instrument() { - return faker.resolve("music.instruments"); - } + public String instrument() { + return faker.resolve("music.instruments"); + } - public String key() { - return faker.options().option(KEYS) + faker.options().option(KEY_VARIANTS); - } + public String key() { + return faker.options().option(KEYS) + faker.options().option(KEY_VARIANTS); + } - public String chord() { - return key() + faker.options().option(CHORD_TYPES); - } + public String chord() { + return key() + faker.options().option(CHORD_TYPES); + } - public String genre() { - return faker.resolve("music.genres"); - } + public String genre() { + return faker.resolve("music.genres"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Name.java b/src/main/java/org/thejavaguy/javafaker/Name.java index a09e26a..dd47dd0 100644 --- a/src/main/java/org/thejavaguy/javafaker/Name.java +++ b/src/main/java/org/thejavaguy/javafaker/Name.java @@ -4,137 +4,146 @@ public class Name { - private final Faker faker; - - /** - * Internal constructor, not to be used by clients. Instances of {@link Name} should be accessed via - * {@link Faker#name()}. - */ - protected Name(Faker faker) { - this.faker = faker; - } - - /** - *

- * A multipart name composed of an optional prefix, a firstname and a lastname - * or other possible variances based on locale. Examples: - *

    - *
  • James Jones Jr.
  • - *
  • Julie Johnson
  • - *
- *

- * @return a random name with given and family names and an optional suffix. - */ - public String name() { - return faker.fakeValuesService().resolve("name.name", this, faker); - } - - /** - *

- * A multipart name composed of an optional prefix, a given and family name, - * another 'firstname' for the middle name and an optional suffix such as Jr. - * Examples: - *

    - *
  • Mrs. Ella Geraldine Fitzgerald
  • - *
  • Jason Tom Sawyer Jr.
  • - *
  • Helen Jessica Troy
  • - *
- *

- * @return a random name with a middle name component with optional prefix and suffix - */ - public String nameWithMiddle() { - return faker.fakeValuesService().resolve("name.name_with_middle", this, faker); - } - - /** - *

Returns the same value as {@link #name()}

- * @see Name#name() - */ - public String fullName() { - return name(); - } - - /** - *

Returns a random 'given' name such as Aaliyah, Aaron, Abagail or Abbey

- * @return a 'given' name such as Aaliyah, Aaron, Abagail or Abbey - */ - public String firstName() { - return faker.fakeValuesService().resolve("name.first_name", this, faker); - } - - /** - *

Returns a random last name such as Smith, Jones or Baldwin

- * @return a random last name such as Smith, Jones or Baldwin - */ - public String lastName() { - return faker.fakeValuesService().resolve("name.last_name", this, faker); - } - - /** - *

Returns a name prefix such as Mr., Mrs., Ms., Miss, or Dr.

- * @return a name prefix such as Mr., Mrs., Ms., Miss, or Dr. - */ - public String prefix() { - return faker.fakeValuesService().resolve("name.prefix", this, faker); - } - - /** - *

Returns a name suffix such as Jr., Sr., I, II, III, IV, V, MD, DDS, PhD or DVM

- * @return a name suffix such as Jr., Sr., I, II, III, IV, V, MD, DDS, PhD or DVM - */ - public String suffix() { - return faker.fakeValuesService().resolve("name.suffix", this, faker); - } - - /** - *

- * A three part title composed of a descriptor level and job. Some examples are : - *

    - *
  • (template) {descriptor} {level} {job}
  • - *
  • Lead Solutions Specialist
  • - *
  • National Marketing Manager
  • - *
  • Central Response Liaison
  • - *
- *

- * @return a random three part job title - */ - public String title() { - return StringUtils.join(new String[] { - faker.fakeValuesService().resolve("name.title.descriptor", this, faker), - faker.fakeValuesService().resolve("name.title.level", this, faker), - faker.fakeValuesService().resolve("name.title.job", this, faker) }, " "); - } - - /** - *

- * A lowercase username composed of the first_name and last_name joined with a '.'. Some examples are: - *

    - *
  • (template) {@link #firstName()}.{@link #lastName()}
  • - *
  • jim.jones
  • - *
  • jason.leigh
  • - *
  • tracy.jordan
  • - *
- *

- * @return a random two part user name. - * @see Name#firstName() - * @see Name#lastName() - */ - public String username() { - - String username = StringUtils.join( - firstName().replaceAll("'", "").toLowerCase(), - ".", - lastName().replaceAll("'", "").toLowerCase() - ); - - return StringUtils.deleteWhitespace(username); - } - - /** - *

Returns a blood group such as O−, O+, A-, A+, B-, B+, AB-, AB+

- * @return a blood group such as O−, O+, A-, A+, B-, B+, AB-, AB+ - */ - public String bloodGroup() { - return faker.fakeValuesService().resolve("name.blood_group", this, faker); - } + private final Faker faker; + + /** + * Internal constructor, not to be used by clients. Instances of {@link Name} should be accessed + * via {@link Faker#name()}. + */ + protected Name(Faker faker) { + this.faker = faker; + } + + /** + * A multipart name composed of an optional prefix, a firstname and a lastname or other possible + * variances based on locale. Examples: + * + *
    + *
  • James Jones Jr. + *
  • Julie Johnson + *
+ * + * @return a random name with given and family names and an optional suffix. + */ + public String name() { + return faker.fakeValuesService().resolve("name.name", this, faker); + } + + /** + * A multipart name composed of an optional prefix, a given and family name, another 'firstname' + * for the middle name and an optional suffix such as Jr. Examples: + * + *
    + *
  • Mrs. Ella Geraldine Fitzgerald + *
  • Jason Tom Sawyer Jr. + *
  • Helen Jessica Troy + *
+ * + * @return a random name with a middle name component with optional prefix and suffix + */ + public String nameWithMiddle() { + return faker.fakeValuesService().resolve("name.name_with_middle", this, faker); + } + + /** + * Returns the same value as {@link #name()} + * + * @see Name#name() + */ + public String fullName() { + return name(); + } + + /** + * Returns a random 'given' name such as Aaliyah, Aaron, Abagail or Abbey + * + * @return a 'given' name such as Aaliyah, Aaron, Abagail or Abbey + */ + public String firstName() { + return faker.fakeValuesService().resolve("name.first_name", this, faker); + } + + /** + * Returns a random last name such as Smith, Jones or Baldwin + * + * @return a random last name such as Smith, Jones or Baldwin + */ + public String lastName() { + return faker.fakeValuesService().resolve("name.last_name", this, faker); + } + + /** + * Returns a name prefix such as Mr., Mrs., Ms., Miss, or Dr. + * + * @return a name prefix such as Mr., Mrs., Ms., Miss, or Dr. + */ + public String prefix() { + return faker.fakeValuesService().resolve("name.prefix", this, faker); + } + + /** + * Returns a name suffix such as Jr., Sr., I, II, III, IV, V, MD, DDS, PhD or DVM + * + * @return a name suffix such as Jr., Sr., I, II, III, IV, V, MD, DDS, PhD or DVM + */ + public String suffix() { + return faker.fakeValuesService().resolve("name.suffix", this, faker); + } + + /** + * A three part title composed of a descriptor level and job. Some examples are : + * + *
    + *
  • (template) {descriptor} {level} {job} + *
  • Lead Solutions Specialist + *
  • National Marketing Manager + *
  • Central Response Liaison + *
+ * + * @return a random three part job title + */ + public String title() { + return StringUtils.join( + new String[] { + faker.fakeValuesService().resolve("name.title.descriptor", this, faker), + faker.fakeValuesService().resolve("name.title.level", this, faker), + faker.fakeValuesService().resolve("name.title.job", this, faker) + }, + " "); + } + + /** + * A lowercase username composed of the first_name and last_name joined with a '.'. Some examples + * are: + * + *
    + *
  • (template) {@link #firstName()}.{@link #lastName()} + *
  • jim.jones + *
  • jason.leigh + *
  • tracy.jordan + *
+ * + * @return a random two part user name. + * @see Name#firstName() + * @see Name#lastName() + */ + public String username() { + + String username = + StringUtils.join( + firstName().replaceAll("'", "").toLowerCase(), + ".", + lastName().replaceAll("'", "").toLowerCase()); + + return StringUtils.deleteWhitespace(username); + } + + /** + * Returns a blood group such as O−, O+, A-, A+, B-, B+, AB-, AB+ + * + * @return a blood group such as O−, O+, A-, A+, B-, B+, AB-, AB+ + */ + public String bloodGroup() { + return faker.fakeValuesService().resolve("name.blood_group", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Nation.java b/src/main/java/org/thejavaguy/javafaker/Nation.java index 160ee8e..92a7195 100644 --- a/src/main/java/org/thejavaguy/javafaker/Nation.java +++ b/src/main/java/org/thejavaguy/javafaker/Nation.java @@ -8,37 +8,36 @@ public class Nation { - private static final Charset UTF8_CHARSET = StandardCharsets.UTF_8; + private static final Charset UTF8_CHARSET = StandardCharsets.UTF_8; - private final Faker faker; + private final Faker faker; - protected Nation(Faker faker) { - this.faker = faker; - } + protected Nation(Faker faker) { + this.faker = faker; + } - public String nationality() { - return faker.fakeValuesService().resolve("nation.nationality", this, faker); - } + public String nationality() { + return faker.fakeValuesService().resolve("nation.nationality", this, faker); + } - public String language() { - return faker.fakeValuesService().resolve("nation.language", this, faker); - } - - public String capitalCity() { - return faker.fakeValuesService().resolve("nation.capital_city", this, faker); - } + public String language() { + return faker.fakeValuesService().resolve("nation.language", this, faker); + } - public String flag() { - @SuppressWarnings("unchecked") - List flagInts = (List) faker.fakeValuesService().fetch("nation.flag"); + public String capitalCity() { + return faker.fakeValuesService().resolve("nation.capital_city", this, faker); + } - ByteBuffer byteBuffer = MappedByteBuffer.allocate(flagInts.size()); + public String flag() { + @SuppressWarnings("unchecked") + List flagInts = (List) faker.fakeValuesService().fetch("nation.flag"); - for (Integer flagInt : flagInts) { - byteBuffer.put(flagInt.byteValue()); - } + ByteBuffer byteBuffer = MappedByteBuffer.allocate(flagInts.size()); - return new String(byteBuffer.array(), UTF8_CHARSET); + for (Integer flagInt : flagInts) { + byteBuffer.put(flagInt.byteValue()); } + return new String(byteBuffer.array(), UTF8_CHARSET); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Number.java b/src/main/java/org/thejavaguy/javafaker/Number.java index 523d783..3bbb7e0 100644 --- a/src/main/java/org/thejavaguy/javafaker/Number.java +++ b/src/main/java/org/thejavaguy/javafaker/Number.java @@ -4,120 +4,115 @@ import java.math.RoundingMode; public class Number { - private final Faker faker; - - protected Number(Faker faker) { - this.faker = faker; - } - - /** - * Returns a random number from 0-9 (both inclusive) - */ - public int randomDigit() { - return decimalBetween(0,10).intValue(); + private final Faker faker; + + protected Number(Faker faker) { + this.faker = faker; + } + + /** Returns a random number from 0-9 (both inclusive) */ + public int randomDigit() { + return decimalBetween(0, 10).intValue(); + } + + /** Returns a random number from 1-9 (both inclusive) */ + public int randomDigitNotZero() { + return decimalBetween(1, 10).intValue(); + } + + /** + * @see Number#numberBetween(long, long) + */ + public int numberBetween(int min, int max) { + if (min == max) return min; + + int value = decimalBetween(min, max).setScale(0, RoundingMode.HALF_DOWN).intValue(); + return value == max ? value - 1 : value; + } + + /** + * Return a number between min and max. If min == max, then min is returned. So + * numberBetween(2,2) will yield 2 even though it doesn't make sense. + * + * @param min inclusive + * @param max exclusive (unless min == max) + */ + public long numberBetween(long min, long max) { + if (min == max) return min; + + long value = decimalBetween(min, max).setScale(0, RoundingMode.HALF_DOWN).longValue(); + return value == max ? value - 1 : value; + } + + /** + * @param numberOfDigits the number of digits the generated value should have + * @param strict whether or not the generated value should have exactly numberOfDigits + * + */ + public long randomNumber(int numberOfDigits, boolean strict) { + long max = (long) Math.pow(10, numberOfDigits); + if (strict) { + long min = (long) Math.pow(10, numberOfDigits - 1); + return faker.random().nextLong(max - min) + min; } - /** - * Returns a random number from 1-9 (both inclusive) - */ - public int randomDigitNotZero() { - return decimalBetween(1,10).intValue(); + return faker.random().nextLong(max); + } + + /** Returns a random number */ + public long randomNumber() { + int numberOfDigits = decimalBetween(1, 10).intValue(); + return randomNumber(numberOfDigits, false); + } + + public double randomDouble(int maxNumberOfDecimals, int min, int max) { + return randomDouble(maxNumberOfDecimals, (long) min, (long) max); + } + + /** + * Returns a random double + * + * @param maxNumberOfDecimals maximum number of places + * @param min minimum value + * @param max maximum value + */ + public double randomDouble(int maxNumberOfDecimals, long min, long max) { + return decimalBetween(min, max) + .setScale(maxNumberOfDecimals, RoundingMode.HALF_DOWN) + .doubleValue(); + } + + /** + * @param min inclusive + * @param max exclusive + * @return + */ + private BigDecimal decimalBetween(long min, long max) { + if (min == max) { + return new BigDecimal(min); } + final long trueMin = Math.min(min, max); + final long trueMax = Math.max(min, max); - /** - * @see Number#numberBetween(long, long) - */ - public int numberBetween(int min, int max) { - if (min == max) return min; - - int value = decimalBetween(min,max).setScale(0, RoundingMode.HALF_DOWN).intValue(); - return value == max ? value - 1 : value; - } + final double range = (double) trueMax - (double) trueMin; - /** - * Return a number between min and max. If - * min == max, then min is returned. So numberBetween(2,2) will yield 2 even though - * it doesn't make sense. - * - * @param min inclusive - * @param max exclusive (unless min == max) - */ - public long numberBetween(long min, long max) { - if (min == max) return min; - - long value = decimalBetween(min, max).setScale(0, RoundingMode.HALF_DOWN).longValue(); - return value == max ? value - 1 : value; - } + final double chunkCount = Math.sqrt(Math.abs(range)); + final long randomChunk = faker.random().nextLong((long) chunkCount); - /** - * @param numberOfDigits the number of digits the generated value should have - * @param strict whether or not the generated value should have exactly numberOfDigits - */ - public long randomNumber(int numberOfDigits, boolean strict) { - long max = (long) Math.pow(10, numberOfDigits); - if (strict) { - long min = (long) Math.pow(10, numberOfDigits - 1); - return faker.random().nextLong(max - min) + min; - } - - return faker.random().nextLong(max); - } + final double chunkStart = trueMin + randomChunk * chunkCount; + final double adj = chunkCount * faker.random().nextDouble(); + return new BigDecimal(chunkStart + adj); + } - /** - * Returns a random number - */ - public long randomNumber() { - int numberOfDigits = decimalBetween(1,10).intValue(); - return randomNumber(numberOfDigits, false); + public String digits(int count) { + final StringBuilder tmp = new StringBuilder(); + for (int i = 0; i < count; i++) { + tmp.append(randomDigit()); } + return tmp.toString(); + } - public double randomDouble(int maxNumberOfDecimals, int min, int max) { - return randomDouble(maxNumberOfDecimals,(long) min, (long) max); - } - /** - * Returns a random double - * - * @param maxNumberOfDecimals maximum number of places - * @param min minimum value - * @param max maximum value - */ - public double randomDouble(int maxNumberOfDecimals, long min, long max) { - return decimalBetween(min,max) - .setScale(maxNumberOfDecimals, RoundingMode.HALF_DOWN) - .doubleValue(); - } - - /** - * @param min inclusive - * @param max exclusive - * @return - */ - private BigDecimal decimalBetween(long min, long max) { - if (min == max) { - return new BigDecimal(min); - } - final long trueMin = Math.min(min, max); - final long trueMax = Math.max(min, max); - - final double range = (double) trueMax - (double) trueMin; - - final double chunkCount = Math.sqrt(Math.abs(range)); - final long randomChunk = faker.random().nextLong((long) chunkCount); - - final double chunkStart = trueMin + randomChunk * chunkCount; - final double adj = chunkCount * faker.random().nextDouble(); - return new BigDecimal(chunkStart + adj); - } - - public String digits(int count) { - final StringBuilder tmp = new StringBuilder(); - for (int i = 0; i < count; i++) { - tmp.append(randomDigit()); - } - return tmp.toString(); - } - - public String digit() { - return digits(1); - } + public String digit() { + return digits(1); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Options.java b/src/main/java/org/thejavaguy/javafaker/Options.java index e6b1420..f24d75b 100644 --- a/src/main/java/org/thejavaguy/javafaker/Options.java +++ b/src/main/java/org/thejavaguy/javafaker/Options.java @@ -3,53 +3,53 @@ import java.util.List; public class Options { - private final Faker faker; + private final Faker faker; - protected Options(Faker faker) { - this.faker = faker; - } + protected Options(Faker faker) { + this.faker = faker; + } - /** - * Returns a random element from an varargs. - * - * @param options The varargs to take a random element from. - * @param The type of the elements in the varargs. - * @return A randomly selected element from the varargs. - */ - public E option(E... options) { - return options[faker.random().nextInt(options.length)]; - } + /** + * Returns a random element from an varargs. + * + * @param options The varargs to take a random element from. + * @param The type of the elements in the varargs. + * @return A randomly selected element from the varargs. + */ + public E option(E... options) { + return options[faker.random().nextInt(options.length)]; + } - /** - * Returns a random element from Enum. - * - * @param enumeration The Enum to take a random element from. - * @return A randomly selected element from the enum. - */ - public > E option(Class enumeration) { - E[] enumConstants = enumeration.getEnumConstants(); - return enumConstants[faker.random().nextInt(enumConstants.length)]; - } + /** + * Returns a random element from Enum. + * + * @param enumeration The Enum to take a random element from. + * @return A randomly selected element from the enum. + */ + public > E option(Class enumeration) { + E[] enumConstants = enumeration.getEnumConstants(); + return enumConstants[faker.random().nextInt(enumConstants.length)]; + } - /** - * Returns a random element from an array. - * - * @param array The array to take a random element from. - * @param The type of the elements in the array. - * @return A randomly selected element from the array. - */ - public E nextElement(E[] array) { - return array[faker.random().nextInt(array.length)]; - } + /** + * Returns a random element from an array. + * + * @param array The array to take a random element from. + * @param The type of the elements in the array. + * @return A randomly selected element from the array. + */ + public E nextElement(E[] array) { + return array[faker.random().nextInt(array.length)]; + } - /** - * Returns a random element from a list. - * - * @param list The list to take a random element from. - * @param The type of the elements in the list. - * @return A randomly selected element from the list. - */ - public E nextElement(List list) { - return list.get(faker.random().nextInt(list.size())); - } + /** + * Returns a random element from a list. + * + * @param list The list to take a random element from. + * @param The type of the elements in the list. + * @return A randomly selected element from the list. + */ + public E nextElement(List list) { + return list.get(faker.random().nextInt(list.size())); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Overwatch.java b/src/main/java/org/thejavaguy/javafaker/Overwatch.java index bb41bc1..651155c 100644 --- a/src/main/java/org/thejavaguy/javafaker/Overwatch.java +++ b/src/main/java/org/thejavaguy/javafaker/Overwatch.java @@ -1,21 +1,21 @@ package org.thejavaguy.javafaker; public class Overwatch { - private final Faker faker; + private final Faker faker; - protected Overwatch(Faker faker) { - this.faker = faker; - } + protected Overwatch(Faker faker) { + this.faker = faker; + } - public String hero() { - return faker.fakeValuesService().resolve("games.overwatch.heroes", this, faker); - } + public String hero() { + return faker.fakeValuesService().resolve("games.overwatch.heroes", this, faker); + } - public String location() { - return faker.fakeValuesService().resolve("games.overwatch.locations", this, faker); - } + public String location() { + return faker.fakeValuesService().resolve("games.overwatch.locations", this, faker); + } - public String quote() { - return faker.fakeValuesService().resolve("games.overwatch.quotes", this, faker); - } + public String quote() { + return faker.fakeValuesService().resolve("games.overwatch.quotes", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/PhoneNumber.java b/src/main/java/org/thejavaguy/javafaker/PhoneNumber.java index 313ba14..8a51d2e 100644 --- a/src/main/java/org/thejavaguy/javafaker/PhoneNumber.java +++ b/src/main/java/org/thejavaguy/javafaker/PhoneNumber.java @@ -1,29 +1,29 @@ package org.thejavaguy.javafaker; public class PhoneNumber { - private final Faker faker; + private final Faker faker; - protected PhoneNumber(Faker faker) { - this.faker = faker; - } + protected PhoneNumber(Faker faker) { + this.faker = faker; + } - public String cellPhone() { - return faker.numerify(faker.fakeValuesService().resolve("cell_phone.formats", this, faker)); - } + public String cellPhone() { + return faker.numerify(faker.fakeValuesService().resolve("cell_phone.formats", this, faker)); + } - public String phoneNumber() { - return faker.numerify(faker.fakeValuesService().resolve("phone_number.formats", this, faker)); - } + public String phoneNumber() { + return faker.numerify(faker.fakeValuesService().resolve("phone_number.formats", this, faker)); + } - public String extension() { - return subscriberNumber(); - } + public String extension() { + return subscriberNumber(); + } - public String subscriberNumber(int length) { - return faker.numerify("#".repeat(Math.max(0, length))); - } + public String subscriberNumber(int length) { + return faker.numerify("#".repeat(Math.max(0, length))); + } - public String subscriberNumber() { - return subscriberNumber(4); - } + public String subscriberNumber() { + return subscriberNumber(4); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Photography.java b/src/main/java/org/thejavaguy/javafaker/Photography.java index b745ac5..a14bcb7 100644 --- a/src/main/java/org/thejavaguy/javafaker/Photography.java +++ b/src/main/java/org/thejavaguy/javafaker/Photography.java @@ -1,76 +1,74 @@ package org.thejavaguy.javafaker; -/** - * Provides photography related strings. - */ +/** Provides photography related strings. */ public class Photography { - private final Faker faker; + private final Faker faker; - protected Photography(Faker faker) { - this.faker = faker; - } + protected Photography(Faker faker) { + this.faker = faker; + } - /** - * @return a photography term. - */ - public String term() { - return faker.fakeValuesService().fetchString("photography.term"); - } + /** + * @return a photography term. + */ + public String term() { + return faker.fakeValuesService().fetchString("photography.term"); + } - /** - * @return a photography brand. - */ - public String brand() { - return faker.fakeValuesService().fetchString("photography.brand"); - } + /** + * @return a photography brand. + */ + public String brand() { + return faker.fakeValuesService().fetchString("photography.brand"); + } - /** - * @return a name of camera model/make. - */ - public String camera() { - return faker.fakeValuesService().fetchString("photography.camera"); - } + /** + * @return a name of camera model/make. + */ + public String camera() { + return faker.fakeValuesService().fetchString("photography.camera"); + } - /** - * @return some lens description like 500mm/8. - */ - public String lens() { - return faker.fakeValuesService().fetchString("photography.lens"); - } + /** + * @return some lens description like 500mm/8. + */ + public String lens() { + return faker.fakeValuesService().fetchString("photography.lens"); + } - /** - * @return a photography genre. - */ - public String genre() { - return faker.fakeValuesService().fetchString("photography.genre"); - } + /** + * @return a photography genre. + */ + public String genre() { + return faker.fakeValuesService().fetchString("photography.genre"); + } - /** - * @return some string to tag an image. - */ - public String imageTag() { - return faker.fakeValuesService().fetchString("photography.imagetag"); - } + /** + * @return some string to tag an image. + */ + public String imageTag() { + return faker.fakeValuesService().fetchString("photography.imagetag"); + } - /** - * @return some aperture description like f/1.4 . - */ - public String aperture() { - return faker.fakeValuesService().fetchString("photography.aperture"); - } + /** + * @return some aperture description like f/1.4 . + */ + public String aperture() { + return faker.fakeValuesService().fetchString("photography.aperture"); + } - /** - * @return some shutter description like 1/25 . - */ - public String shutter() { - return faker.fakeValuesService().fetchString("photography.shutter"); - } + /** + * @return some shutter description like 1/25 . + */ + public String shutter() { + return faker.fakeValuesService().fetchString("photography.shutter"); + } - /** - * @return some ISO value like 3200. - */ - public String iso() { - return faker.fakeValuesService().fetchString("photography.iso"); - } + /** + * @return some ISO value like 3200. + */ + public String iso() { + return faker.fakeValuesService().fetchString("photography.iso"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Pokemon.java b/src/main/java/org/thejavaguy/javafaker/Pokemon.java index 4d90b2c..3b7fccb 100644 --- a/src/main/java/org/thejavaguy/javafaker/Pokemon.java +++ b/src/main/java/org/thejavaguy/javafaker/Pokemon.java @@ -2,17 +2,17 @@ public class Pokemon { - private final Faker faker; + private final Faker faker; - protected Pokemon(Faker faker) { - this.faker = faker; - } + protected Pokemon(Faker faker) { + this.faker = faker; + } - public String name() { - return faker.resolve("games.pokemon.names"); - } + public String name() { + return faker.resolve("games.pokemon.names"); + } - public String location() { - return faker.resolve("games.pokemon.locations"); - } + public String location() { + return faker.resolve("games.pokemon.locations"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/PrincessBride.java b/src/main/java/org/thejavaguy/javafaker/PrincessBride.java index 177ffe7..84dc97f 100644 --- a/src/main/java/org/thejavaguy/javafaker/PrincessBride.java +++ b/src/main/java/org/thejavaguy/javafaker/PrincessBride.java @@ -1,17 +1,17 @@ package org.thejavaguy.javafaker; public class PrincessBride { - private final Faker faker; + private final Faker faker; - protected PrincessBride(Faker faker) { - this.faker = faker; - } + protected PrincessBride(Faker faker) { + this.faker = faker; + } - public String character() { - return faker.resolve("princess_bride.characters"); - } + public String character() { + return faker.resolve("princess_bride.characters"); + } - public String quote() { - return faker.resolve("princess_bride.quotes"); - } + public String quote() { + return faker.resolve("princess_bride.quotes"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/ProgrammingLanguage.java b/src/main/java/org/thejavaguy/javafaker/ProgrammingLanguage.java index 6a852b9..6f5b9b3 100644 --- a/src/main/java/org/thejavaguy/javafaker/ProgrammingLanguage.java +++ b/src/main/java/org/thejavaguy/javafaker/ProgrammingLanguage.java @@ -2,18 +2,17 @@ public class ProgrammingLanguage { - private final Faker faker; + private final Faker faker; - public ProgrammingLanguage(Faker faker) { - this.faker = faker; - } + public ProgrammingLanguage(Faker faker) { + this.faker = faker; + } - public String name() { - return faker.fakeValuesService().resolve("programming_language.name", this, faker); - } - - public String creator() { - return faker.fakeValuesService().resolve("programming_language.creator", this, faker); - } + public String name() { + return faker.fakeValuesService().resolve("programming_language.name", this, faker); + } + public String creator() { + return faker.fakeValuesService().resolve("programming_language.creator", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Relationships.java b/src/main/java/org/thejavaguy/javafaker/Relationships.java index 8ea1452..a11dccd 100644 --- a/src/main/java/org/thejavaguy/javafaker/Relationships.java +++ b/src/main/java/org/thejavaguy/javafaker/Relationships.java @@ -8,56 +8,56 @@ import java.util.stream.Collectors; public class Relationships { - private final Faker faker; - - protected Relationships(final Faker faker) { - this.faker = faker; - } - - public String direct() { - return faker.resolve("relationship.familial.direct"); - } - - public String extended() { - return faker.resolve("relationship.familial.extended"); - } - - public String inLaw() { - return faker.resolve("relationship.in_law"); - } - - public String spouse() { - return faker.resolve("relationship.spouse"); - } - - public String parent() { - return faker.resolve("relationship.parent"); - } - - public String sibling() { - return faker.resolve("relationship.sibling"); - } - - public String any() { - try { - Method[] methods = Relationships.class.getDeclaredMethods(); - List filteredMethods = Arrays.stream(methods) - .filter(method -> method.getModifiers() == Modifier.PUBLIC) - .filter(method -> !method.getName().equals("any")) - .collect(Collectors.toList()); - int indx = faker.random().nextInt(filteredMethods.size()); - Method runMethod = filteredMethods.get(indx); - Relationships relationships = new Relationships(faker); - return (String)runMethod.invoke(relationships); - } catch (SecurityException e) { - throw new RuntimeException("SecurityException: " + e.getMessage(), e); - } catch (IllegalArgumentException e) { - throw new RuntimeException("IllegalArgumentException: " + e.getMessage(), e); - } catch (IllegalAccessException e) { - throw new RuntimeException("IllegalAccessException: " + e.getMessage(), e); - } catch (InvocationTargetException e) { - throw new RuntimeException("InvocationTargetException: " + e.getMessage(), e); - } - } - + private final Faker faker; + + protected Relationships(final Faker faker) { + this.faker = faker; + } + + public String direct() { + return faker.resolve("relationship.familial.direct"); + } + + public String extended() { + return faker.resolve("relationship.familial.extended"); + } + + public String inLaw() { + return faker.resolve("relationship.in_law"); + } + + public String spouse() { + return faker.resolve("relationship.spouse"); + } + + public String parent() { + return faker.resolve("relationship.parent"); + } + + public String sibling() { + return faker.resolve("relationship.sibling"); + } + + public String any() { + try { + Method[] methods = Relationships.class.getDeclaredMethods(); + List filteredMethods = + Arrays.stream(methods) + .filter(method -> method.getModifiers() == Modifier.PUBLIC) + .filter(method -> !method.getName().equals("any")) + .collect(Collectors.toList()); + int indx = faker.random().nextInt(filteredMethods.size()); + Method runMethod = filteredMethods.get(indx); + Relationships relationships = new Relationships(faker); + return (String) runMethod.invoke(relationships); + } catch (SecurityException e) { + throw new RuntimeException("SecurityException: " + e.getMessage(), e); + } catch (IllegalArgumentException e) { + throw new RuntimeException("IllegalArgumentException: " + e.getMessage(), e); + } catch (IllegalAccessException e) { + throw new RuntimeException("IllegalAccessException: " + e.getMessage(), e); + } catch (InvocationTargetException e) { + throw new RuntimeException("InvocationTargetException: " + e.getMessage(), e); + } + } } diff --git a/src/main/java/org/thejavaguy/javafaker/RickAndMorty.java b/src/main/java/org/thejavaguy/javafaker/RickAndMorty.java index 336f462..cc032e1 100644 --- a/src/main/java/org/thejavaguy/javafaker/RickAndMorty.java +++ b/src/main/java/org/thejavaguy/javafaker/RickAndMorty.java @@ -1,21 +1,21 @@ package org.thejavaguy.javafaker; -public class RickAndMorty { - private final Faker faker; +public class RickAndMorty { + private final Faker faker; - protected RickAndMorty(final Faker faker) { - this.faker = faker; - } + protected RickAndMorty(final Faker faker) { + this.faker = faker; + } - public String character() { - return faker.resolve("rick_and_morty.characters"); - } + public String character() { + return faker.resolve("rick_and_morty.characters"); + } - public String location() { - return faker.resolve("rick_and_morty.locations"); - } + public String location() { + return faker.resolve("rick_and_morty.locations"); + } - public String quote() { - return faker.resolve("rick_and_morty.quotes"); - } + public String quote() { + return faker.resolve("rick_and_morty.quotes"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Robin.java b/src/main/java/org/thejavaguy/javafaker/Robin.java index 267b764..3b643f1 100644 --- a/src/main/java/org/thejavaguy/javafaker/Robin.java +++ b/src/main/java/org/thejavaguy/javafaker/Robin.java @@ -1,13 +1,13 @@ package org.thejavaguy.javafaker; public class Robin { - private final Faker faker; + private final Faker faker; - protected Robin(Faker faker) { - this.faker = faker; - } + protected Robin(Faker faker) { + this.faker = faker; + } - public String quote() { - return faker.fakeValuesService().resolve("robin.quotes", this, faker); - } + public String quote() { + return faker.fakeValuesService().resolve("robin.quotes", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/RockBand.java b/src/main/java/org/thejavaguy/javafaker/RockBand.java index 1f1475e..e85a0bd 100644 --- a/src/main/java/org/thejavaguy/javafaker/RockBand.java +++ b/src/main/java/org/thejavaguy/javafaker/RockBand.java @@ -2,13 +2,13 @@ public class RockBand { - private final Faker faker; + private final Faker faker; - protected RockBand(Faker faker) { - this.faker = faker; - } + protected RockBand(Faker faker) { + this.faker = faker; + } - public String name() { - return faker.resolve("rock_band.name"); - } + public String name() { + return faker.resolve("rock_band.name"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Shakespeare.java b/src/main/java/org/thejavaguy/javafaker/Shakespeare.java index 2a07c14..b19a367 100644 --- a/src/main/java/org/thejavaguy/javafaker/Shakespeare.java +++ b/src/main/java/org/thejavaguy/javafaker/Shakespeare.java @@ -2,84 +2,86 @@ public class Shakespeare { - private static final String [] hamletQuotes = { - "To be, or not to be: that is the question.", - "Neither a borrower nor a lender be; For loan oft loses both itself and friend, and borrowing dulls the edge of husbandry.", - "This above all: to thine own self be true.", - "Though this be madness, yet there is method in 't.", - "That it should come to this!.", - "There is nothing either good or bad, but thinking makes it so.", - "What a piece of work is man! how noble in reason! how infinite in faculty! in form and moving how express and admirable! in action how like an angel! in apprehension how like a god! the beauty of the world, the paragon of animals! .", - "The lady doth protest too much, methinks.", - "In my mind's eye.", - "A little more than kin, and less than kind.", - "The play 's the thing wherein I'll catch the conscience of the king.", - "And it must follow, as the night the day, thou canst not then be false to any man.", - "Brevity is the soul of wit.", - "Doubt that the sun doth move, doubt truth to be a liar, but never doubt I love.", - "Rich gifts wax poor when givers prove unkind.", - "Do you think I am easier to be played on than a pipe?", - "I will speak daggers to her, but use none.", - "When sorrows come, they come not single spies, but in battalions." }; + private static final String[] hamletQuotes = { + "To be, or not to be: that is the question.", + "Neither a borrower nor a lender be; For loan oft loses both itself and friend, and borrowing dulls the edge of husbandry.", + "This above all: to thine own self be true.", + "Though this be madness, yet there is method in 't.", + "That it should come to this!.", + "There is nothing either good or bad, but thinking makes it so.", + "What a piece of work is man! how noble in reason! how infinite in faculty! in form and moving how express and admirable! in action how like an angel! in apprehension how like a god! the beauty of the world, the paragon of animals! .", + "The lady doth protest too much, methinks.", + "In my mind's eye.", + "A little more than kin, and less than kind.", + "The play 's the thing wherein I'll catch the conscience of the king.", + "And it must follow, as the night the day, thou canst not then be false to any man.", + "Brevity is the soul of wit.", + "Doubt that the sun doth move, doubt truth to be a liar, but never doubt I love.", + "Rich gifts wax poor when givers prove unkind.", + "Do you think I am easier to be played on than a pipe?", + "I will speak daggers to her, but use none.", + "When sorrows come, they come not single spies, but in battalions." + }; - private static final String [] asYouLikeItQuotes = { - "All the world 's a stage, and all the men and women merely players. They have their exits and their entrances; And one man in his time plays many parts.", - "Can one desire too much of a good thing?.", - "I like this place and willingly could waste my time in it.", - "How bitter a thing it is to look into happiness through another man's eyes!", - "Blow, blow, thou winter wind! Thou art not so unkind as man's ingratitude.", - "True is it that we have seen better days.", - "For ever and a day.", - "The fool doth think he is wise, but the wise man knows himself to be a fool." }; + private static final String[] asYouLikeItQuotes = { + "All the world 's a stage, and all the men and women merely players. They have their exits and their entrances; And one man in his time plays many parts.", + "Can one desire too much of a good thing?.", + "I like this place and willingly could waste my time in it.", + "How bitter a thing it is to look into happiness through another man's eyes!", + "Blow, blow, thou winter wind! Thou art not so unkind as man's ingratitude.", + "True is it that we have seen better days.", + "For ever and a day.", + "The fool doth think he is wise, but the wise man knows himself to be a fool." + }; - private static final String [] kingRichardIIIQuotes = { - "Now is the winter of our discontent.", - "A horse! a horse! my kingdom for a horse!.", - "Conscience is but a word that cowards use, devised at first to keep the strong in awe.", - "So wise so young, they say, do never live long.", - "Off with his head!", - "An honest tale speeds best, being plainly told.", - "The king's name is a tower of strength.", - "The world is grown so bad, that wrens make prey where eagles dare not perch." }; + private static final String[] kingRichardIIIQuotes = { + "Now is the winter of our discontent.", + "A horse! a horse! my kingdom for a horse!.", + "Conscience is but a word that cowards use, devised at first to keep the strong in awe.", + "So wise so young, they say, do never live long.", + "Off with his head!", + "An honest tale speeds best, being plainly told.", + "The king's name is a tower of strength.", + "The world is grown so bad, that wrens make prey where eagles dare not perch." + }; - private static final String [] romeoAndJulietQuotes = { - "O Romeo, Romeo! wherefore art thou Romeo?.", - "It is the east, and Juliet is the sun.", - "Good Night, Good night! Parting is such sweet sorrow, that I shall say good night till it be morrow.", - "What's in a name? That which we call a rose by any other name would smell as sweet.", - "Wisely and slow; they stumble that run fast.", - "Tempt not a desperate man.", - "For you and I are past our dancing days.", - "O! she doth teach the torches to burn bright.", - "It seems she hangs upon the cheek of night like a rich jewel in an Ethiope's ear.", - "See, how she leans her cheek upon her hand! O that I were a glove upon that hand, that I might touch that cheek!.", - "Not stepping o'er the bounds of modesty." }; + private static final String[] romeoAndJulietQuotes = { + "O Romeo, Romeo! wherefore art thou Romeo?.", + "It is the east, and Juliet is the sun.", + "Good Night, Good night! Parting is such sweet sorrow, that I shall say good night till it be morrow.", + "What's in a name? That which we call a rose by any other name would smell as sweet.", + "Wisely and slow; they stumble that run fast.", + "Tempt not a desperate man.", + "For you and I are past our dancing days.", + "O! she doth teach the torches to burn bright.", + "It seems she hangs upon the cheek of night like a rich jewel in an Ethiope's ear.", + "See, how she leans her cheek upon her hand! O that I were a glove upon that hand, that I might touch that cheek!.", + "Not stepping o'er the bounds of modesty." + }; + private final Faker faker; - private final Faker faker; + protected Shakespeare(Faker faker) { + this.faker = faker; + } - protected Shakespeare(Faker faker) { - this.faker = faker; - } + public String hamletQuote() { + return randomElement(hamletQuotes); + } - public String hamletQuote() { - return randomElement(hamletQuotes); - } + public String asYouLikeItQuote() { + return randomElement(asYouLikeItQuotes); + } - public String asYouLikeItQuote() { - return randomElement(asYouLikeItQuotes); - } + public String kingRichardIIIQuote() { + return randomElement(kingRichardIIIQuotes); + } - public String kingRichardIIIQuote() { - return randomElement(kingRichardIIIQuotes); - } - - public String romeoAndJulietQuote() { - return randomElement(romeoAndJulietQuotes); - } - - private String randomElement(String[] values) { - return values[faker.random().nextInt(values.length)]; - } + public String romeoAndJulietQuote() { + return randomElement(romeoAndJulietQuotes); + } + private String randomElement(String[] values) { + return values[faker.random().nextInt(values.length)]; + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Shipping.java b/src/main/java/org/thejavaguy/javafaker/Shipping.java index 78f05fb..e605fb2 100644 --- a/src/main/java/org/thejavaguy/javafaker/Shipping.java +++ b/src/main/java/org/thejavaguy/javafaker/Shipping.java @@ -13,367 +13,374 @@ */ public class Shipping { - private final Faker faker; - - protected Shipping(Faker faker) { - this.faker = faker; - } - - /** - * Returns a random shipping carrier name. - * - * @return carrier name, e.g., "UPS", "FedEx" - */ - public String carrier() { - return faker.fakeValuesService().fetchString("shipping.carriers"); - } - - /** - * Returns a random shipping method. - * - * @return shipping method, e.g., "Standard Ground", "Overnight" - */ - public String shippingMethod() { - return faker.fakeValuesService().fetchString("shipping.shipping_methods"); - } - - /** - * Returns a random shipping status. - * - * @return status, e.g., "in_transit", "delivered" - */ - public String status() { - return faker.fakeValuesService().fetchString("shipping.statuses"); - } - - /** - * Returns a random package type. - * - * @return package type, e.g., "Box", "Envelope" - */ - public String packageType() { - return faker.fakeValuesService().fetchString("shipping.package_types"); - } - - /** - * Returns a random handling instruction. - * - * @return handling instruction, e.g., "Fragile", "Handle With Care" - */ - public String handlingInstruction() { - return faker.fakeValuesService().fetchString("shipping.handling_instructions"); - } - - /** - * Returns a random shipping exception type. - * - * @return exception type, e.g., "Address Unknown", "Weather Delay" - */ - public String exceptionType() { - return faker.fakeValuesService().fetchString("shipping.exception_types"); - } - - /** - * Generates a tracking number in UPS format. - * - * @return UPS tracking number, e.g., "1ZABC1234567890123456" - */ - public String trackingNumberUps() { - // UPS: 1Z + 6 alphanumeric + 2 digits + 8 digits - return "1Z" + faker.bothify("??????", true) + faker.numerify("##########"); - } - - /** - * Generates a tracking number in FedEx Express format. - * - * @return FedEx tracking number, e.g., "1234-5678-9012" - */ - public String trackingNumberFedEx() { - return faker.numerify("####-####-####"); - } - - /** - * Generates a tracking number in USPS format. - * - * @return USPS tracking number, e.g., "9400111899223100001234" - */ - public String trackingNumberUsps() { - // USPS typically 20-22 digits - return faker.numerify("94001118992231########"); - } - - /** - * Generates a tracking number in DHL format. - * - * @return DHL tracking number, e.g., "1234567890" - */ - public String trackingNumberDhl() { - return faker.numerify("##########"); - } - - /** - * Generates a tracking number for a random carrier. - * - * @return tracking number in carrier-appropriate format - */ - public String trackingNumber() { - int choice = faker.random().nextInt(4); - switch (choice) { - case 0: return trackingNumberUps(); - case 1: return trackingNumberFedEx(); - case 2: return trackingNumberUsps(); - default: return trackingNumberDhl(); - } - } - - /** - * Generates an order/shipment ID. - * - * @return shipment ID, e.g., "SHP-20241115-ABC123" - */ - public String shipmentId() { - String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); - return "SHP-" + date + "-" + faker.bothify("???###", true); - } - - /** - * Generates a package weight. - * - * @return weight in pounds, e.g., 2.5 - */ - public BigDecimal weight() { - return weight(0.1, 50.0); - } - - /** - * Generates a package weight within range. - * - * @param min minimum weight - * @param max maximum weight - * @return weight as BigDecimal with 1 decimal place - */ - public BigDecimal weight(double min, double max) { - double w = min + (faker.random().nextDouble() * (max - min)); - return BigDecimal.valueOf(w).setScale(1, RoundingMode.HALF_UP); - } - - /** - * Generates formatted weight with unit. - * - * @return formatted weight, e.g., "2.5 lb" - */ - public String weightFormatted() { - String unit = faker.fakeValuesService().fetchString("shipping.weight_units"); - return weight() + " " + unit; - } - - /** - * Generates package dimensions (length x width x height). - * - * @return dimensions string, e.g., "12 x 8 x 4 in" - */ - public String dimensions() { - int length = faker.random().nextInt(30) + 4; - int width = faker.random().nextInt(20) + 3; - int height = faker.random().nextInt(15) + 2; - String unit = faker.fakeValuesService().fetchString("shipping.dimension_units"); - return length + " x " + width + " x " + height + " " + unit; - } - - /** - * Generates individual dimension values. - * - * @return array of [length, width, height] in inches - */ - public int[] dimensionValues() { - int length = faker.random().nextInt(30) + 4; - int width = faker.random().nextInt(20) + 3; - int height = faker.random().nextInt(15) + 2; - return new int[]{length, width, height}; - } - - /** - * Generates a shipping cost. - * - * @return shipping cost as BigDecimal - */ - public BigDecimal shippingCost() { - return shippingCost(5.99, 99.99); - } - - /** - * Generates a shipping cost within range. - * - * @param min minimum cost - * @param max maximum cost - * @return shipping cost as BigDecimal with 2 decimal places - */ - public BigDecimal shippingCost(double min, double max) { - double cost = min + (faker.random().nextDouble() * (max - min)); - return BigDecimal.valueOf(cost).setScale(2, RoundingMode.HALF_UP); - } - - /** - * Generates formatted shipping cost. - * - * @return formatted cost, e.g., "$12.99" - */ - public String shippingCostFormatted() { - return "$" + shippingCost().toString(); - } - - /** - * Generates an estimated delivery date (3-14 days from now). - * - * @return estimated delivery date - */ - public LocalDate estimatedDeliveryDate() { - int daysAhead = faker.random().nextInt(12) + 3; - return LocalDate.now().plusDays(daysAhead); - } - - /** - * Generates a ship date (within last 7 days). - * - * @return ship date - */ - public LocalDate shipDate() { - int daysBack = faker.random().nextInt(7); - return LocalDate.now().minusDays(daysBack); - } - - /** - * Generates an actual delivery timestamp. - * - * @return delivery datetime - */ - public LocalDateTime deliveryDateTime() { - LocalDate date = LocalDate.now().minusDays(faker.random().nextInt(7)); - int hour = faker.random().nextInt(12) + 8; // 8 AM to 8 PM - int minute = faker.random().nextInt(60); - return date.atTime(hour, minute); - } - - /** - * Generates a formatted delivery time window. - * - * @return delivery window, e.g., "2:00 PM - 6:00 PM" - */ - public String deliveryWindow() { - String[] windows = { - "8:00 AM - 12:00 PM", - "9:00 AM - 1:00 PM", - "12:00 PM - 4:00 PM", - "2:00 PM - 6:00 PM", - "4:00 PM - 8:00 PM" - }; - return windows[faker.random().nextInt(windows.length)]; - } - - /** - * Generates a package insured value. - * - * @return insured value as BigDecimal - */ - public BigDecimal insuredValue() { - double value = faker.random().nextDouble() * 1000; - return BigDecimal.valueOf(value).setScale(2, RoundingMode.HALF_UP); - } - - /** - * Generates a COD (Cash on Delivery) amount. - * - * @return COD amount as BigDecimal - */ - public BigDecimal codAmount() { - double amount = 10 + (faker.random().nextDouble() * 490); - return BigDecimal.valueOf(amount).setScale(2, RoundingMode.HALF_UP); - } - - /** - * Generates a reference number (PO number, order number). - * - * @return reference number, e.g., "PO-12345678" - */ - public String referenceNumber() { - String[] prefixes = {"PO-", "REF-", "ORD-", "INV-", ""}; - String prefix = prefixes[faker.random().nextInt(prefixes.length)]; - return prefix + faker.numerify("########"); - } - - /** - * Generates a location/facility name for tracking updates. - * - * @return location, e.g., "Chicago, IL Distribution Center" - */ - public String facilityLocation() { - String city = faker.address().city(); - String state = faker.address().stateAbbr(); - String[] types = {"Distribution Center", "Hub", "Sort Facility", "Processing Center", "Delivery Station"}; - String type = types[faker.random().nextInt(types.length)]; - return city + ", " + state + " " + type; - } - - /** - * Generates a barcode number for package labels. - * - * @return barcode number (20 digits) - */ - public String barcode() { - return faker.numerify("####################"); - } - - /** - * Generates a zone number for shipping rate calculation. - * - * @return zone number 1-8 - */ - public int zone() { - return faker.random().nextInt(8) + 1; - } - - /** - * Returns whether signature is required (random). - * - * @return true or false - */ - public boolean signatureRequired() { - return faker.random().nextBoolean(); - } - - /** - * Returns whether the package contains hazardous materials (random, low probability). - * - * @return true ~10% of the time - */ - public boolean hazardousMaterials() { - return faker.random().nextInt(10) == 0; - } - - /** - * Generates a tracking event description. - * - * @return tracking event, e.g., "Package arrived at Chicago, IL Hub" - */ - public String trackingEvent() { - String status = status(); - String location = facilityLocation(); - - switch (status) { - case "label_created": - return "Shipping label created"; - case "picked_up": - return "Package picked up from sender"; - case "in_transit": - return "Package arrived at " + location; - case "out_for_delivery": - return "Out for delivery"; - case "delivered": - return "Delivered"; - case "attempted_delivery": - return "Delivery attempted - " + faker.fakeValuesService().fetchString("shipping.exception_types"); - default: - return "Package in transit at " + location; - } - } + private final Faker faker; + + protected Shipping(Faker faker) { + this.faker = faker; + } + + /** + * Returns a random shipping carrier name. + * + * @return carrier name, e.g., "UPS", "FedEx" + */ + public String carrier() { + return faker.fakeValuesService().fetchString("shipping.carriers"); + } + + /** + * Returns a random shipping method. + * + * @return shipping method, e.g., "Standard Ground", "Overnight" + */ + public String shippingMethod() { + return faker.fakeValuesService().fetchString("shipping.shipping_methods"); + } + + /** + * Returns a random shipping status. + * + * @return status, e.g., "in_transit", "delivered" + */ + public String status() { + return faker.fakeValuesService().fetchString("shipping.statuses"); + } + + /** + * Returns a random package type. + * + * @return package type, e.g., "Box", "Envelope" + */ + public String packageType() { + return faker.fakeValuesService().fetchString("shipping.package_types"); + } + + /** + * Returns a random handling instruction. + * + * @return handling instruction, e.g., "Fragile", "Handle With Care" + */ + public String handlingInstruction() { + return faker.fakeValuesService().fetchString("shipping.handling_instructions"); + } + + /** + * Returns a random shipping exception type. + * + * @return exception type, e.g., "Address Unknown", "Weather Delay" + */ + public String exceptionType() { + return faker.fakeValuesService().fetchString("shipping.exception_types"); + } + + /** + * Generates a tracking number in UPS format. + * + * @return UPS tracking number, e.g., "1ZABC1234567890123456" + */ + public String trackingNumberUps() { + // UPS: 1Z + 6 alphanumeric + 2 digits + 8 digits + return "1Z" + faker.bothify("??????", true) + faker.numerify("##########"); + } + + /** + * Generates a tracking number in FedEx Express format. + * + * @return FedEx tracking number, e.g., "1234-5678-9012" + */ + public String trackingNumberFedEx() { + return faker.numerify("####-####-####"); + } + + /** + * Generates a tracking number in USPS format. + * + * @return USPS tracking number, e.g., "9400111899223100001234" + */ + public String trackingNumberUsps() { + // USPS typically 20-22 digits + return faker.numerify("94001118992231########"); + } + + /** + * Generates a tracking number in DHL format. + * + * @return DHL tracking number, e.g., "1234567890" + */ + public String trackingNumberDhl() { + return faker.numerify("##########"); + } + + /** + * Generates a tracking number for a random carrier. + * + * @return tracking number in carrier-appropriate format + */ + public String trackingNumber() { + int choice = faker.random().nextInt(4); + switch (choice) { + case 0: + return trackingNumberUps(); + case 1: + return trackingNumberFedEx(); + case 2: + return trackingNumberUsps(); + default: + return trackingNumberDhl(); + } + } + + /** + * Generates an order/shipment ID. + * + * @return shipment ID, e.g., "SHP-20241115-ABC123" + */ + public String shipmentId() { + String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); + return "SHP-" + date + "-" + faker.bothify("???###", true); + } + + /** + * Generates a package weight. + * + * @return weight in pounds, e.g., 2.5 + */ + public BigDecimal weight() { + return weight(0.1, 50.0); + } + + /** + * Generates a package weight within range. + * + * @param min minimum weight + * @param max maximum weight + * @return weight as BigDecimal with 1 decimal place + */ + public BigDecimal weight(double min, double max) { + double w = min + (faker.random().nextDouble() * (max - min)); + return BigDecimal.valueOf(w).setScale(1, RoundingMode.HALF_UP); + } + + /** + * Generates formatted weight with unit. + * + * @return formatted weight, e.g., "2.5 lb" + */ + public String weightFormatted() { + String unit = faker.fakeValuesService().fetchString("shipping.weight_units"); + return weight() + " " + unit; + } + + /** + * Generates package dimensions (length x width x height). + * + * @return dimensions string, e.g., "12 x 8 x 4 in" + */ + public String dimensions() { + int length = faker.random().nextInt(30) + 4; + int width = faker.random().nextInt(20) + 3; + int height = faker.random().nextInt(15) + 2; + String unit = faker.fakeValuesService().fetchString("shipping.dimension_units"); + return length + " x " + width + " x " + height + " " + unit; + } + + /** + * Generates individual dimension values. + * + * @return array of [length, width, height] in inches + */ + public int[] dimensionValues() { + int length = faker.random().nextInt(30) + 4; + int width = faker.random().nextInt(20) + 3; + int height = faker.random().nextInt(15) + 2; + return new int[] {length, width, height}; + } + + /** + * Generates a shipping cost. + * + * @return shipping cost as BigDecimal + */ + public BigDecimal shippingCost() { + return shippingCost(5.99, 99.99); + } + + /** + * Generates a shipping cost within range. + * + * @param min minimum cost + * @param max maximum cost + * @return shipping cost as BigDecimal with 2 decimal places + */ + public BigDecimal shippingCost(double min, double max) { + double cost = min + (faker.random().nextDouble() * (max - min)); + return BigDecimal.valueOf(cost).setScale(2, RoundingMode.HALF_UP); + } + + /** + * Generates formatted shipping cost. + * + * @return formatted cost, e.g., "$12.99" + */ + public String shippingCostFormatted() { + return "$" + shippingCost().toString(); + } + + /** + * Generates an estimated delivery date (3-14 days from now). + * + * @return estimated delivery date + */ + public LocalDate estimatedDeliveryDate() { + int daysAhead = faker.random().nextInt(12) + 3; + return LocalDate.now().plusDays(daysAhead); + } + + /** + * Generates a ship date (within last 7 days). + * + * @return ship date + */ + public LocalDate shipDate() { + int daysBack = faker.random().nextInt(7); + return LocalDate.now().minusDays(daysBack); + } + + /** + * Generates an actual delivery timestamp. + * + * @return delivery datetime + */ + public LocalDateTime deliveryDateTime() { + LocalDate date = LocalDate.now().minusDays(faker.random().nextInt(7)); + int hour = faker.random().nextInt(12) + 8; // 8 AM to 8 PM + int minute = faker.random().nextInt(60); + return date.atTime(hour, minute); + } + + /** + * Generates a formatted delivery time window. + * + * @return delivery window, e.g., "2:00 PM - 6:00 PM" + */ + public String deliveryWindow() { + String[] windows = { + "8:00 AM - 12:00 PM", + "9:00 AM - 1:00 PM", + "12:00 PM - 4:00 PM", + "2:00 PM - 6:00 PM", + "4:00 PM - 8:00 PM" + }; + return windows[faker.random().nextInt(windows.length)]; + } + + /** + * Generates a package insured value. + * + * @return insured value as BigDecimal + */ + public BigDecimal insuredValue() { + double value = faker.random().nextDouble() * 1000; + return BigDecimal.valueOf(value).setScale(2, RoundingMode.HALF_UP); + } + + /** + * Generates a COD (Cash on Delivery) amount. + * + * @return COD amount as BigDecimal + */ + public BigDecimal codAmount() { + double amount = 10 + (faker.random().nextDouble() * 490); + return BigDecimal.valueOf(amount).setScale(2, RoundingMode.HALF_UP); + } + + /** + * Generates a reference number (PO number, order number). + * + * @return reference number, e.g., "PO-12345678" + */ + public String referenceNumber() { + String[] prefixes = {"PO-", "REF-", "ORD-", "INV-", ""}; + String prefix = prefixes[faker.random().nextInt(prefixes.length)]; + return prefix + faker.numerify("########"); + } + + /** + * Generates a location/facility name for tracking updates. + * + * @return location, e.g., "Chicago, IL Distribution Center" + */ + public String facilityLocation() { + String city = faker.address().city(); + String state = faker.address().stateAbbr(); + String[] types = { + "Distribution Center", "Hub", "Sort Facility", "Processing Center", "Delivery Station" + }; + String type = types[faker.random().nextInt(types.length)]; + return city + ", " + state + " " + type; + } + + /** + * Generates a barcode number for package labels. + * + * @return barcode number (20 digits) + */ + public String barcode() { + return faker.numerify("####################"); + } + + /** + * Generates a zone number for shipping rate calculation. + * + * @return zone number 1-8 + */ + public int zone() { + return faker.random().nextInt(8) + 1; + } + + /** + * Returns whether signature is required (random). + * + * @return true or false + */ + public boolean signatureRequired() { + return faker.random().nextBoolean(); + } + + /** + * Returns whether the package contains hazardous materials (random, low probability). + * + * @return true ~10% of the time + */ + public boolean hazardousMaterials() { + return faker.random().nextInt(10) == 0; + } + + /** + * Generates a tracking event description. + * + * @return tracking event, e.g., "Package arrived at Chicago, IL Hub" + */ + public String trackingEvent() { + String status = status(); + String location = facilityLocation(); + + switch (status) { + case "label_created": + return "Shipping label created"; + case "picked_up": + return "Package picked up from sender"; + case "in_transit": + return "Package arrived at " + location; + case "out_for_delivery": + return "Out for delivery"; + case "delivered": + return "Delivered"; + case "attempted_delivery": + return "Delivery attempted - " + + faker.fakeValuesService().fetchString("shipping.exception_types"); + default: + return "Package in transit at " + location; + } + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Sip.java b/src/main/java/org/thejavaguy/javafaker/Sip.java index e21ec35..1b2e484 100644 --- a/src/main/java/org/thejavaguy/javafaker/Sip.java +++ b/src/main/java/org/thejavaguy/javafaker/Sip.java @@ -10,206 +10,223 @@ * @author TomerFi */ public final class Sip { - private final Faker faker; - private final ArrayList portPool; - - Sip(final Faker faker) { - this.faker = faker; - int port = 40000; - portPool = new ArrayList<>(); - while (port <= 50000) { - portPool.add(port); - port = port + 2; - } - } - - /** - * The various SIP methods are listed in https://en.wikipedia.org/wiki/Session_Initiation_Protocol. - * - * @return a SIP method String, e.g. {@code INVITE}. - */ - public String method() { - return faker.resolve("sip.methods"); - } - - /** - * Content types are based on https://tools.ietf.org/html/rfc5621 and - * https://tools.ietf.org/html/rfc3261. - * - * @return a SIP content-type declaration String, e.g. {@code application/sdp} - */ - public String contentType() { - return faker.resolve("sip.content.types"); - } - - /** - * Get a 4 digit random port for SIP messaging. - * - * @return a SIP messaging port int, e.g. 5060. - */ - public int messagingPort() { - return faker.random().nextInt(1000, 9999); - } - - /** - * Get a 5 digit positive even port for rtp udp communication. - * - * @return an RTP UDP 5 digit port int, e.g. 40002. - */ - public int rtpPort() { - return portPool.get(faker.random().nextInt(0, portPool.size())); - } - - /** - * Proviosional code, the various response codes are listed in - * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. - * - * @return a 3 digit SIP provisioan response code between 100 and 199 int, e.g. {@code 180}. - */ - public int provisionalResponseCode() { - return Integer.parseInt(faker.resolve("sip.response.codes.provisional")); - } - - /** - * Success code, the various response codes are listed in - * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. - * - * @return a 3 digit SIP success response code between 200 and 299 int, e.g. {@code 200}. - */ - public int successResponseCode() { - return Integer.parseInt(faker.resolve("sip.response.codes.success")); - } - - /** - * Redirection code, the various response codes are listed in - * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. - * - * @return a 3 digit SIP redirection response code between 300 and 399 int, e.g. {@code 301}. - */ - public int redirectResponseCode() { - return Integer.parseInt(faker.resolve("sip.response.codes.redirection")); - } - - /** - * Client error code, the various response codes are listed in - * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. - * - * @return a 3 digit SIP client error response code between 400 and 499 int, e.g. {@code 486}. - */ - public int clientErrorResponseCode() { - return Integer.parseInt(faker.resolve("sip.response.codes.clientError")); - } - - /** - * Server error code, the various response codes are listed in - * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. - * - * @return a 3 digit SIP server error response code between 500 and 599 int, e.g. {@code 503}. - */ - public int serverErrorResponseCode() { - return Integer.parseInt(faker.resolve("sip.response.codes.serverError")); - } - - /** - * Global error code, the various response codes are listed in - * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. - * - * @return a 3 digit SIP global error response code between 600 and 699 int, e.g. {@code 608}. - */ - public int globalErrorResponseCode() { - return Integer.parseInt(faker.resolve("sip.response.codes.globalError")); - } - - /** - * Proviosional phrase, the various response phrases are listed in - * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. - * - * @return a SIP provisional response phrase String, e.g. {@code Ringing}. - */ - public String provisionalResponsePhrase() { - return faker.resolve("sip.response.phrases.provisional"); - } - - /** - * Success phrase, the various response phrases are listed in - * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. - * - * @return a SIP success response phrase String, e.g. {@code OK}. - */ - public String successResponsePhrase() { - return faker.resolve("sip.response.phrases.success"); - } - - /** - * Redirection phrase, the various response phrases are listed in - * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. - * - * @return a SIP redirection response phrase String, e.g. {@code Moved Permanently}. - */ - public String redirectResponsePhrase() { - return faker.resolve("sip.response.phrases.redirection"); - } - - /** - * Client error phrase, the various response phrases are listed in - * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. - * - * @return a SIP client error response phrase String, e.g. {@code Busy Here}. - */ - public String clientErrorResponsePhrase() { - return faker.resolve("sip.response.phrases.clientError"); - } - - /** - * Server error phrase, the various response phrases are listed in - * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. - * - * @return a SIP server erro response phrase String, e.g. {@code Service Unavailable}. - */ - public String serverErrorResponsePhrase() { - return faker.resolve("sip.response.phrases.serverError"); - } - - /** - * Server error phrase, the various response phrases are listed in - * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. - * - * @return a SIP global error response phrase String, e.g. {@code Rejected}. - */ - public String globalErrorResponsePhrase() { - return faker.resolve("sip.response.phrases.globalError"); - } - - /** - * Body example of SDP type can be found in https://tools.ietf.org/html/rfc5621. - * - * @return a fake SDP type SIP body String. - */ - public String bodyString() { - return "v=0\n" + - "o=" + faker.name().firstName() + " " + faker.internet().uuid() + " IN IP4 " + faker.internet().domainName() + "\n" + - "s=-\n" + - "c=IN IP4 " + faker.internet().ipV4Address() + "\n" + - "t=0 0\n" + - "m=audio " + rtpPort() + " RTP/AVP 0\n" + - "a=rtpmap:0 PCMU/8000"; - } - - /** - * Body example of SDP type can be found in https://tools.ietf.org/html/rfc5621. - * - * @return a fake SDP type SIP body byte array. - */ - public byte[] bodyBytes() { - return bodyString().getBytes(UTF_8); - } - - /** - * Return a valid name address to use with {@code to/from} headers. - * - * @return a valid name address String, e.g. {@code }. - */ - public String nameAddress() { - return ""; - } + private final Faker faker; + private final ArrayList portPool; + + Sip(final Faker faker) { + this.faker = faker; + int port = 40000; + portPool = new ArrayList<>(); + while (port <= 50000) { + portPool.add(port); + port = port + 2; + } + } + + /** + * The various SIP methods are listed in + * https://en.wikipedia.org/wiki/Session_Initiation_Protocol. + * + * @return a SIP method String, e.g. {@code INVITE}. + */ + public String method() { + return faker.resolve("sip.methods"); + } + + /** + * Content types are based on https://tools.ietf.org/html/rfc5621 and + * https://tools.ietf.org/html/rfc3261. + * + * @return a SIP content-type declaration String, e.g. {@code application/sdp} + */ + public String contentType() { + return faker.resolve("sip.content.types"); + } + + /** + * Get a 4 digit random port for SIP messaging. + * + * @return a SIP messaging port int, e.g. 5060. + */ + public int messagingPort() { + return faker.random().nextInt(1000, 9999); + } + + /** + * Get a 5 digit positive even port for rtp udp communication. + * + * @return an RTP UDP 5 digit port int, e.g. 40002. + */ + public int rtpPort() { + return portPool.get(faker.random().nextInt(0, portPool.size())); + } + + /** + * Proviosional code, the various response codes are listed in + * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. + * + * @return a 3 digit SIP provisioan response code between 100 and 199 int, e.g. {@code 180}. + */ + public int provisionalResponseCode() { + return Integer.parseInt(faker.resolve("sip.response.codes.provisional")); + } + + /** + * Success code, the various response codes are listed in + * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. + * + * @return a 3 digit SIP success response code between 200 and 299 int, e.g. {@code 200}. + */ + public int successResponseCode() { + return Integer.parseInt(faker.resolve("sip.response.codes.success")); + } + + /** + * Redirection code, the various response codes are listed in + * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. + * + * @return a 3 digit SIP redirection response code between 300 and 399 int, e.g. {@code 301}. + */ + public int redirectResponseCode() { + return Integer.parseInt(faker.resolve("sip.response.codes.redirection")); + } + + /** + * Client error code, the various response codes are listed in + * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. + * + * @return a 3 digit SIP client error response code between 400 and 499 int, e.g. {@code 486}. + */ + public int clientErrorResponseCode() { + return Integer.parseInt(faker.resolve("sip.response.codes.clientError")); + } + + /** + * Server error code, the various response codes are listed in + * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. + * + * @return a 3 digit SIP server error response code between 500 and 599 int, e.g. {@code 503}. + */ + public int serverErrorResponseCode() { + return Integer.parseInt(faker.resolve("sip.response.codes.serverError")); + } + + /** + * Global error code, the various response codes are listed in + * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. + * + * @return a 3 digit SIP global error response code between 600 and 699 int, e.g. {@code 608}. + */ + public int globalErrorResponseCode() { + return Integer.parseInt(faker.resolve("sip.response.codes.globalError")); + } + + /** + * Proviosional phrase, the various response phrases are listed in + * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. + * + * @return a SIP provisional response phrase String, e.g. {@code Ringing}. + */ + public String provisionalResponsePhrase() { + return faker.resolve("sip.response.phrases.provisional"); + } + + /** + * Success phrase, the various response phrases are listed in + * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. + * + * @return a SIP success response phrase String, e.g. {@code OK}. + */ + public String successResponsePhrase() { + return faker.resolve("sip.response.phrases.success"); + } + + /** + * Redirection phrase, the various response phrases are listed in + * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. + * + * @return a SIP redirection response phrase String, e.g. {@code Moved Permanently}. + */ + public String redirectResponsePhrase() { + return faker.resolve("sip.response.phrases.redirection"); + } + + /** + * Client error phrase, the various response phrases are listed in + * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. + * + * @return a SIP client error response phrase String, e.g. {@code Busy Here}. + */ + public String clientErrorResponsePhrase() { + return faker.resolve("sip.response.phrases.clientError"); + } + + /** + * Server error phrase, the various response phrases are listed in + * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. + * + * @return a SIP server erro response phrase String, e.g. {@code Service Unavailable}. + */ + public String serverErrorResponsePhrase() { + return faker.resolve("sip.response.phrases.serverError"); + } + + /** + * Server error phrase, the various response phrases are listed in + * https://en.wikipedia.org/wiki/List_of_SIP_response_codes. + * + * @return a SIP global error response phrase String, e.g. {@code Rejected}. + */ + public String globalErrorResponsePhrase() { + return faker.resolve("sip.response.phrases.globalError"); + } + + /** + * Body example of SDP type can be found in https://tools.ietf.org/html/rfc5621. + * + * @return a fake SDP type SIP body String. + */ + public String bodyString() { + return "v=0\n" + + "o=" + + faker.name().firstName() + + " " + + faker.internet().uuid() + + " IN IP4 " + + faker.internet().domainName() + + "\n" + + "s=-\n" + + "c=IN IP4 " + + faker.internet().ipV4Address() + + "\n" + + "t=0 0\n" + + "m=audio " + + rtpPort() + + " RTP/AVP 0\n" + + "a=rtpmap:0 PCMU/8000"; + } + + /** + * Body example of SDP type can be found in https://tools.ietf.org/html/rfc5621. + * + * @return a fake SDP type SIP body byte array. + */ + public byte[] bodyBytes() { + return bodyString().getBytes(UTF_8); + } + + /** + * Return a valid name address to use with {@code to/from} headers. + * + * @return a valid name address String, e.g. {@code }. + */ + public String nameAddress() { + return ""; + } } diff --git a/src/main/java/org/thejavaguy/javafaker/SlackEmoji.java b/src/main/java/org/thejavaguy/javafaker/SlackEmoji.java index bb01b86..588bbd9 100644 --- a/src/main/java/org/thejavaguy/javafaker/SlackEmoji.java +++ b/src/main/java/org/thejavaguy/javafaker/SlackEmoji.java @@ -2,45 +2,45 @@ public class SlackEmoji { - private final Faker faker; + private final Faker faker; - protected SlackEmoji(Faker faker) { - this.faker = faker; - } + protected SlackEmoji(Faker faker) { + this.faker = faker; + } - public String people() { - return faker.resolve("slack_emoji.people"); - } + public String people() { + return faker.resolve("slack_emoji.people"); + } - public String nature() { - return faker.resolve("slack_emoji.nature"); - } + public String nature() { + return faker.resolve("slack_emoji.nature"); + } - public String foodAndDrink() { - return faker.resolve("slack_emoji.food_and_drink"); - } + public String foodAndDrink() { + return faker.resolve("slack_emoji.food_and_drink"); + } - public String celebration() { - return faker.resolve("slack_emoji.celebration"); - } + public String celebration() { + return faker.resolve("slack_emoji.celebration"); + } - public String activity() { - return faker.resolve("slack_emoji.activity"); - } + public String activity() { + return faker.resolve("slack_emoji.activity"); + } - public String travelAndPlaces() { - return faker.resolve("slack_emoji.travel_and_places"); - } + public String travelAndPlaces() { + return faker.resolve("slack_emoji.travel_and_places"); + } - public String objectsAndSymbols() { - return faker.resolve("slack_emoji.objects_and_symbols"); - } + public String objectsAndSymbols() { + return faker.resolve("slack_emoji.objects_and_symbols"); + } - public String custom() { - return faker.resolve("slack_emoji.custom"); - } + public String custom() { + return faker.resolve("slack_emoji.custom"); + } - public String emoji() { - return faker.fakeValuesService().resolve("slack_emoji.emoji", this, faker); - } + public String emoji() { + return faker.fakeValuesService().resolve("slack_emoji.emoji", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Space.java b/src/main/java/org/thejavaguy/javafaker/Space.java index 453fa12..1baeded 100644 --- a/src/main/java/org/thejavaguy/javafaker/Space.java +++ b/src/main/java/org/thejavaguy/javafaker/Space.java @@ -2,61 +2,63 @@ public class Space { - private final Faker faker; + private final Faker faker; - protected Space(Faker faker) { - this.faker = faker; - } + protected Space(Faker faker) { + this.faker = faker; + } - public String planet() { - return faker.resolve("space.planet"); - } + public String planet() { + return faker.resolve("space.planet"); + } - public String moon() { - return faker.resolve("space.moon"); - } + public String moon() { + return faker.resolve("space.moon"); + } - public String galaxy() { - return faker.resolve("space.galaxy"); - } + public String galaxy() { + return faker.resolve("space.galaxy"); + } - public String nebula() { - return faker.resolve("space.nebula"); - } + public String nebula() { + return faker.resolve("space.nebula"); + } - public String starCluster() { - return faker.resolve("space.star_cluster"); - } + public String starCluster() { + return faker.resolve("space.star_cluster"); + } - public String constellation() { - return faker.resolve("space.constellation"); - } + public String constellation() { + return faker.resolve("space.constellation"); + } - public String star() { - return faker.resolve("space.star"); - } + public String star() { + return faker.resolve("space.star"); + } - public String agency() { - return faker.resolve("space.agency"); - } + public String agency() { + return faker.resolve("space.agency"); + } - public String agencyAbbreviation() { - return faker.resolve("space.agency_abv"); - } + public String agencyAbbreviation() { + return faker.resolve("space.agency_abv"); + } - public String nasaSpaceCraft() { - return faker.resolve("space.nasa_space_craft"); - } + public String nasaSpaceCraft() { + return faker.resolve("space.nasa_space_craft"); + } - public String company() { - return faker.resolve("space.company"); - } + public String company() { + return faker.resolve("space.company"); + } - public String distanceMeasurement() { - return faker.number().numberBetween(10, 100) + ' ' + faker.resolve("space.distance_measurement"); - } + public String distanceMeasurement() { + return faker.number().numberBetween(10, 100) + + ' ' + + faker.resolve("space.distance_measurement"); + } - public String meteorite() { - return faker.resolve("space.meteorite"); - } + public String meteorite() { + return faker.resolve("space.meteorite"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/StarCraft.java b/src/main/java/org/thejavaguy/javafaker/StarCraft.java index 1ac1904..d23e2eb 100644 --- a/src/main/java/org/thejavaguy/javafaker/StarCraft.java +++ b/src/main/java/org/thejavaguy/javafaker/StarCraft.java @@ -2,26 +2,25 @@ public class StarCraft { - private final Faker faker; + private final Faker faker; - protected StarCraft(final Faker faker) { - this.faker = faker; - } + protected StarCraft(final Faker faker) { + this.faker = faker; + } - public String unit() { - return faker.fakeValuesService().resolve("starcraft.units", this, faker); - } + public String unit() { + return faker.fakeValuesService().resolve("starcraft.units", this, faker); + } - public String building() { - return faker.fakeValuesService().resolve("starcraft.buildings", this, faker); - } + public String building() { + return faker.fakeValuesService().resolve("starcraft.buildings", this, faker); + } - public String character() { - return faker.fakeValuesService().resolve("starcraft.characters", this, faker); - } - - public String planet() { - return faker.fakeValuesService().resolve("starcraft.planets", this, faker); - } + public String character() { + return faker.fakeValuesService().resolve("starcraft.characters", this, faker); + } + public String planet() { + return faker.fakeValuesService().resolve("starcraft.planets", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/StarTrek.java b/src/main/java/org/thejavaguy/javafaker/StarTrek.java index 1788c95..8b0458a 100644 --- a/src/main/java/org/thejavaguy/javafaker/StarTrek.java +++ b/src/main/java/org/thejavaguy/javafaker/StarTrek.java @@ -1,29 +1,29 @@ package org.thejavaguy.javafaker; public class StarTrek { - private final Faker faker; + private final Faker faker; - protected StarTrek(Faker faker) { - this.faker = faker; - } + protected StarTrek(Faker faker) { + this.faker = faker; + } - public String character() { - return faker.fakeValuesService().resolve("star_trek.character", this, faker); - } + public String character() { + return faker.fakeValuesService().resolve("star_trek.character", this, faker); + } - public String location() { - return faker.fakeValuesService().resolve("star_trek.location", this, faker); - } + public String location() { + return faker.fakeValuesService().resolve("star_trek.location", this, faker); + } - public String specie() { - return faker.fakeValuesService().resolve("star_trek.specie", this, faker); - } + public String specie() { + return faker.fakeValuesService().resolve("star_trek.specie", this, faker); + } - public String villain() { - return faker.fakeValuesService().resolve("star_trek.villain", this, faker); - } + public String villain() { + return faker.fakeValuesService().resolve("star_trek.villain", this, faker); + } - public String klingon() { - return faker.fakeValuesService().resolve("star_trek.klingon", this, faker); - } + public String klingon() { + return faker.fakeValuesService().resolve("star_trek.klingon", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Stock.java b/src/main/java/org/thejavaguy/javafaker/Stock.java index 0b8a33d..8fad539 100644 --- a/src/main/java/org/thejavaguy/javafaker/Stock.java +++ b/src/main/java/org/thejavaguy/javafaker/Stock.java @@ -2,18 +2,17 @@ public class Stock { - private final Faker faker; + private final Faker faker; - protected Stock(Faker faker) { - this.faker = faker; - } + protected Stock(Faker faker) { + this.faker = faker; + } - public String nsdqSymbol() { - return faker.fakeValuesService().resolve("stock.symbol_nsdq", this, faker); - } - - public String nyseSymbol() { - return faker.fakeValuesService().resolve("stock.symbol_nyse", this, faker); - } + public String nsdqSymbol() { + return faker.fakeValuesService().resolve("stock.symbol_nsdq", this, faker); + } + public String nyseSymbol() { + return faker.fakeValuesService().resolve("stock.symbol_nyse", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Superhero.java b/src/main/java/org/thejavaguy/javafaker/Superhero.java index f0038f2..69a73c6 100644 --- a/src/main/java/org/thejavaguy/javafaker/Superhero.java +++ b/src/main/java/org/thejavaguy/javafaker/Superhero.java @@ -1,29 +1,29 @@ package org.thejavaguy.javafaker; public class Superhero { - private final Faker faker; + private final Faker faker; - protected Superhero(Faker faker) { - this.faker = faker; - } + protected Superhero(Faker faker) { + this.faker = faker; + } - public String name() { - return faker.fakeValuesService().resolve("superhero.name", this, faker); - } + public String name() { + return faker.fakeValuesService().resolve("superhero.name", this, faker); + } - public String prefix() { - return faker.fakeValuesService().resolve("superhero.prefix", this, faker); - } + public String prefix() { + return faker.fakeValuesService().resolve("superhero.prefix", this, faker); + } - public String suffix() { - return faker.fakeValuesService().resolve("superhero.suffix", this, faker); - } + public String suffix() { + return faker.fakeValuesService().resolve("superhero.suffix", this, faker); + } - public String power() { - return faker.fakeValuesService().resolve("superhero.power", this, faker); - } + public String power() { + return faker.fakeValuesService().resolve("superhero.power", this, faker); + } - public String descriptor() { - return faker.fakeValuesService().resolve("superhero.descriptor", this, faker); - } + public String descriptor() { + return faker.fakeValuesService().resolve("superhero.descriptor", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Team.java b/src/main/java/org/thejavaguy/javafaker/Team.java index 6a6eea3..70129da 100644 --- a/src/main/java/org/thejavaguy/javafaker/Team.java +++ b/src/main/java/org/thejavaguy/javafaker/Team.java @@ -1,25 +1,25 @@ package org.thejavaguy.javafaker; public class Team { - private final Faker faker; + private final Faker faker; - protected Team(Faker faker) { - this.faker = faker; - } + protected Team(Faker faker) { + this.faker = faker; + } - public String name() { - return faker.fakeValuesService().resolve("team.name", this, faker); - } + public String name() { + return faker.fakeValuesService().resolve("team.name", this, faker); + } - public String creature() { - return faker.fakeValuesService().resolve("team.creature", this, faker); - } + public String creature() { + return faker.fakeValuesService().resolve("team.creature", this, faker); + } - public String state() { - return faker.fakeValuesService().resolve("address.state", this, faker); - } + public String state() { + return faker.fakeValuesService().resolve("address.state", this, faker); + } - public String sport() { - return faker.fakeValuesService().resolve("team.sport", this, faker); - } + public String sport() { + return faker.fakeValuesService().resolve("team.sport", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/TwinPeaks.java b/src/main/java/org/thejavaguy/javafaker/TwinPeaks.java index 619c7fe..49e819b 100644 --- a/src/main/java/org/thejavaguy/javafaker/TwinPeaks.java +++ b/src/main/java/org/thejavaguy/javafaker/TwinPeaks.java @@ -1,21 +1,21 @@ package org.thejavaguy.javafaker; public class TwinPeaks { - private final Faker faker; + private final Faker faker; - protected TwinPeaks(final Faker faker) { - this.faker = faker; - } + protected TwinPeaks(final Faker faker) { + this.faker = faker; + } - public String character() { - return faker.resolve("twin_peaks.characters"); - } + public String character() { + return faker.resolve("twin_peaks.characters"); + } - public String location() { - return faker.resolve("twin_peaks.locations"); - } + public String location() { + return faker.resolve("twin_peaks.locations"); + } - public String quote() { - return faker.resolve("twin_peaks.quotes"); - } + public String quote() { + return faker.resolve("twin_peaks.quotes"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/University.java b/src/main/java/org/thejavaguy/javafaker/University.java index c0d134c..c052d66 100644 --- a/src/main/java/org/thejavaguy/javafaker/University.java +++ b/src/main/java/org/thejavaguy/javafaker/University.java @@ -1,21 +1,21 @@ package org.thejavaguy.javafaker; public class University { - private final Faker faker; + private final Faker faker; - protected University(Faker faker) { - this.faker = faker; - } + protected University(Faker faker) { + this.faker = faker; + } - public String name() { - return faker.fakeValuesService().resolve("university.name", this, faker); - } + public String name() { + return faker.fakeValuesService().resolve("university.name", this, faker); + } - public String prefix() { - return faker.fakeValuesService().resolve("university.prefix", this, faker); - } + public String prefix() { + return faker.fakeValuesService().resolve("university.prefix", this, faker); + } - public String suffix() { - return faker.fakeValuesService().resolve("university.suffix", this, faker); - } + public String suffix() { + return faker.fakeValuesService().resolve("university.suffix", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Weather.java b/src/main/java/org/thejavaguy/javafaker/Weather.java index 01b6564..a62d4e9 100644 --- a/src/main/java/org/thejavaguy/javafaker/Weather.java +++ b/src/main/java/org/thejavaguy/javafaker/Weather.java @@ -1,65 +1,65 @@ package org.thejavaguy.javafaker; -/** - * A generator for Weather data. - */ +/** A generator for Weather data. */ public class Weather { - private static final int DEFAULT_MIN_TEMP_C = -30; - private static final int DEFAULT_MAX_TEMP_C = 38; - private static final int DEFAULT_MIN_TEMP_F = -22; - private static final int DEFAULT_MAX_TEMP_F = 100; + private static final int DEFAULT_MIN_TEMP_C = -30; + private static final int DEFAULT_MAX_TEMP_C = 38; + private static final int DEFAULT_MIN_TEMP_F = -22; + private static final int DEFAULT_MAX_TEMP_F = 100; - private final Faker faker; + private final Faker faker; - protected Weather(Faker faker) { - this.faker = faker; - } + protected Weather(Faker faker) { + this.faker = faker; + } - /** - * Generates a short weather description. - */ - public String description() { - return faker.resolve("weather.description"); - } + /** Generates a short weather description. */ + public String description() { + return faker.resolve("weather.description"); + } - /** - * Generates a random temperature celsius between -30 and 38 degrees. - * @return String that represents temperature in format 5°C - */ - public String temperatureCelsius() { - return temperature(DEFAULT_MIN_TEMP_C, DEFAULT_MAX_TEMP_C, "weather.temperature.celsius"); - } + /** + * Generates a random temperature celsius between -30 and 38 degrees. + * + * @return String that represents temperature in format 5°C + */ + public String temperatureCelsius() { + return temperature(DEFAULT_MIN_TEMP_C, DEFAULT_MAX_TEMP_C, "weather.temperature.celsius"); + } - /** - * Generates a random temperature fahrenheit between -22 and 100 degrees. - * @return String that represents temperature in format 5°F - */ - public String temperatureFahrenheit() { - return temperature(DEFAULT_MIN_TEMP_F, DEFAULT_MAX_TEMP_F, "weather.temperature.fahrenheit"); - } + /** + * Generates a random temperature fahrenheit between -22 and 100 degrees. + * + * @return String that represents temperature in format 5°F + */ + public String temperatureFahrenheit() { + return temperature(DEFAULT_MIN_TEMP_F, DEFAULT_MAX_TEMP_F, "weather.temperature.fahrenheit"); + } - /** - * Generates a random temperature celsius between two temperatures. - * @param minTemperature the minimal temperature - * @param maxTemperature the maximal temperature - * @return String that represents temperature in format 5°C - */ - public String temperatureCelsius(int minTemperature, int maxTemperature) { - return temperature(minTemperature, maxTemperature, "weather.temperature.celsius"); - } + /** + * Generates a random temperature celsius between two temperatures. + * + * @param minTemperature the minimal temperature + * @param maxTemperature the maximal temperature + * @return String that represents temperature in format 5°C + */ + public String temperatureCelsius(int minTemperature, int maxTemperature) { + return temperature(minTemperature, maxTemperature, "weather.temperature.celsius"); + } - /** - * Generates a random temperature fahrenheit between two temperatures. - * @param minTemperature the minimal temperature - * @param maxTemperature the maximal temperature - * @return String that represents temperature in format 5°F - */ - public String temperatureFahrenheit(int minTemperature, int maxTemperature) { - return temperature(minTemperature, maxTemperature, "weather.temperature.fahrenheit"); - } + /** + * Generates a random temperature fahrenheit between two temperatures. + * + * @param minTemperature the minimal temperature + * @param maxTemperature the maximal temperature + * @return String that represents temperature in format 5°F + */ + public String temperatureFahrenheit(int minTemperature, int maxTemperature) { + return temperature(minTemperature, maxTemperature, "weather.temperature.fahrenheit"); + } - private String temperature(int minTemperature, int maxTemperature, String degreeKey) { - return faker.random().nextInt(minTemperature, maxTemperature) + faker.resolve(degreeKey); - } + private String temperature(int minTemperature, int maxTemperature, String degreeKey) { + return faker.random().nextInt(minTemperature, maxTemperature) + faker.resolve(degreeKey); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Witcher.java b/src/main/java/org/thejavaguy/javafaker/Witcher.java index ef7caa5..e73da15 100644 --- a/src/main/java/org/thejavaguy/javafaker/Witcher.java +++ b/src/main/java/org/thejavaguy/javafaker/Witcher.java @@ -1,33 +1,33 @@ package org.thejavaguy.javafaker; public class Witcher { - private final Faker faker; + private final Faker faker; - protected Witcher(Faker faker) { - this.faker = faker; - } + protected Witcher(Faker faker) { + this.faker = faker; + } - public String character() { - return faker.fakeValuesService().resolve("games.witcher.characters", this, faker); - } + public String character() { + return faker.fakeValuesService().resolve("games.witcher.characters", this, faker); + } - public String witcher() { - return faker.fakeValuesService().resolve("games.witcher.witchers", this, faker); - } + public String witcher() { + return faker.fakeValuesService().resolve("games.witcher.witchers", this, faker); + } - public String school() { - return faker.fakeValuesService().resolve("games.witcher.schools", this, faker); - } + public String school() { + return faker.fakeValuesService().resolve("games.witcher.schools", this, faker); + } - public String location() { - return faker.fakeValuesService().resolve("games.witcher.locations", this, faker); - } + public String location() { + return faker.fakeValuesService().resolve("games.witcher.locations", this, faker); + } - public String quote() { - return faker.fakeValuesService().resolve("games.witcher.quotes", this, faker); - } + public String quote() { + return faker.fakeValuesService().resolve("games.witcher.quotes", this, faker); + } - public String monster() { - return faker.fakeValuesService().resolve("games.witcher.monsters", this, faker); - } + public String monster() { + return faker.fakeValuesService().resolve("games.witcher.monsters", this, faker); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Yoda.java b/src/main/java/org/thejavaguy/javafaker/Yoda.java index 5fe422f..85e45eb 100644 --- a/src/main/java/org/thejavaguy/javafaker/Yoda.java +++ b/src/main/java/org/thejavaguy/javafaker/Yoda.java @@ -1,13 +1,13 @@ package org.thejavaguy.javafaker; public class Yoda { - private final Faker faker; + private final Faker faker; - protected Yoda(final Faker faker) { - this.faker = faker; - } + protected Yoda(final Faker faker) { + this.faker = faker; + } - public String quote() { - return faker.resolve("yoda.quotes"); - } + public String quote() { + return faker.resolve("yoda.quotes"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/Zelda.java b/src/main/java/org/thejavaguy/javafaker/Zelda.java index c51fb3d..eb2f4f4 100644 --- a/src/main/java/org/thejavaguy/javafaker/Zelda.java +++ b/src/main/java/org/thejavaguy/javafaker/Zelda.java @@ -1,17 +1,17 @@ package org.thejavaguy.javafaker; public class Zelda { - private final Faker faker; + private final Faker faker; - protected Zelda(final Faker faker) { - this.faker = faker; - } + protected Zelda(final Faker faker) { + this.faker = faker; + } - public String game() { - return faker.resolve("games.zelda.games"); - } + public String game() { + return faker.resolve("games.zelda.games"); + } - public String character() { - return faker.resolve("games.zelda.characters"); - } + public String character() { + return faker.resolve("games.zelda.characters"); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/idnumbers/EnIdNumber.java b/src/main/java/org/thejavaguy/javafaker/idnumbers/EnIdNumber.java index 2073dd8..6b4e539 100644 --- a/src/main/java/org/thejavaguy/javafaker/idnumbers/EnIdNumber.java +++ b/src/main/java/org/thejavaguy/javafaker/idnumbers/EnIdNumber.java @@ -3,26 +3,27 @@ import org.thejavaguy.javafaker.Faker; public class EnIdNumber { - private static final String[] invalidSSNPatterns = { - "0{3}-\\\\d{2}-\\\\d{4}", - "\\d{3}-0{2}-\\d{4}", - "\\d{3}-\\d{2}-0{4}", - "666-\\d{2}-\\d{4}", - "9\\d{2}-\\d{2}-\\d{4}"}; + private static final String[] invalidSSNPatterns = { + "0{3}-\\\\d{2}-\\\\d{4}", + "\\d{3}-0{2}-\\d{4}", + "\\d{3}-\\d{2}-0{4}", + "666-\\d{2}-\\d{4}", + "9\\d{2}-\\d{2}-\\d{4}" + }; - public String getValidSsn(Faker f) { - String ssn = f.regexify("[0-8]\\d{2}-\\d{2}-\\d{4}"); + public String getValidSsn(Faker f) { + String ssn = f.regexify("[0-8]\\d{2}-\\d{2}-\\d{4}"); - boolean isValid = true; - for (String invalidSSNPattern : invalidSSNPatterns) { - if (ssn.matches(invalidSSNPattern)) { - isValid = false; - break; - } - } - if (!isValid) { - ssn = getValidSsn(f); - } - return ssn; + boolean isValid = true; + for (String invalidSSNPattern : invalidSSNPatterns) { + if (ssn.matches(invalidSSNPattern)) { + isValid = false; + break; + } } + if (!isValid) { + ssn = getValidSsn(f); + } + return ssn; + } } diff --git a/src/main/java/org/thejavaguy/javafaker/idnumbers/SvSEIdNumber.java b/src/main/java/org/thejavaguy/javafaker/idnumbers/SvSEIdNumber.java index a1edf1d..ba7c193 100644 --- a/src/main/java/org/thejavaguy/javafaker/idnumbers/SvSEIdNumber.java +++ b/src/main/java/org/thejavaguy/javafaker/idnumbers/SvSEIdNumber.java @@ -3,106 +3,105 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; - import org.thejavaguy.javafaker.Faker; /** - * Implementation based on the definition at - * ... - * and the description at - * ... + * Implementation based on the definition at ... + * and the description at ... */ public class SvSEIdNumber { - private static final String[] validPatterns = {"######-####", "######+####"}; - - public String getValidSsn(Faker f) { - String candidate = ""; - while (!validSwedishSsn(candidate)) { - String pattern = getPattern(f); - candidate = f.numerify(pattern); - } + private static final String[] validPatterns = {"######-####", "######+####"}; - return candidate; + public String getValidSsn(Faker f) { + String candidate = ""; + while (!validSwedishSsn(candidate)) { + String pattern = getPattern(f); + candidate = f.numerify(pattern); } - public String getInvalidSsn(Faker f) { - String candidate = "121212-1212"; // Seed with a valid number - while (validSwedishSsn(candidate)) { - String pattern = getPattern(f); - candidate = f.numerify(pattern); - } + return candidate; + } - return candidate; + public String getInvalidSsn(Faker f) { + String candidate = "121212-1212"; // Seed with a valid number + while (validSwedishSsn(candidate)) { + String pattern = getPattern(f); + candidate = f.numerify(pattern); } - private String getPattern(Faker faker) { - return validPatterns[faker.random().nextInt(2)]; - } - - boolean validSwedishSsn(String ssn) { - if (ssn.length() != 11) { - return false; - } - - try { - if (parseDate(ssn)) { - return false; - } - } catch (ParseException e) { - return false; - } - - int calculatedChecksum = calculateChecksum(ssn); - int checksum = Integer.parseInt(ssn.substring(10, 11)); - return checksum == calculatedChecksum; - } + return candidate; + } - private boolean parseDate(String ssn) throws ParseException { - SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd"); - String dateString = ssn.substring(0, 6); - Date date = sdf.parse(dateString); + private String getPattern(Faker faker) { + return validPatterns[faker.random().nextInt(2)]; + } - // want to check that the parsed date is equal to the supplied data, most of the attempts will fail - String reversed = sdf.format(date); - return !reversed.equals(dateString); + boolean validSwedishSsn(String ssn) { + if (ssn.length() != 11) { + return false; } - private int calculateChecksum(String number) { - String dateString = number.substring(0, 6); - String birthNumber = number.substring(7, 10); - - String calculatedNumber = calculateDigits(dateString + birthNumber); - int sum = calculateDigitSum(calculatedNumber); - - int lastDigit = (sum % 10); - int difference = 10 - lastDigit; - - return (difference % 10); + try { + if (parseDate(ssn)) { + return false; + } + } catch (ParseException e) { + return false; } - private String calculateDigits(String numbers) { - String calculatedNumbers = ""; - for (int i = 0; i < 9; i++) { - int res; - int n = Integer.parseInt(numbers.substring(i, i + 1)); - if (i % 2 == 0) { - res = n * 2; - } else { - res = n; - } - - calculatedNumbers += res; - } - return calculatedNumbers; + int calculatedChecksum = calculateChecksum(ssn); + int checksum = Integer.parseInt(ssn.substring(10, 11)); + return checksum == calculatedChecksum; + } + + private boolean parseDate(String ssn) throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd"); + String dateString = ssn.substring(0, 6); + Date date = sdf.parse(dateString); + + // want to check that the parsed date is equal to the supplied data, most of the attempts will + // fail + String reversed = sdf.format(date); + return !reversed.equals(dateString); + } + + private int calculateChecksum(String number) { + String dateString = number.substring(0, 6); + String birthNumber = number.substring(7, 10); + + String calculatedNumber = calculateDigits(dateString + birthNumber); + int sum = calculateDigitSum(calculatedNumber); + + int lastDigit = (sum % 10); + int difference = 10 - lastDigit; + + return (difference % 10); + } + + private String calculateDigits(String numbers) { + String calculatedNumbers = ""; + for (int i = 0; i < 9; i++) { + int res; + int n = Integer.parseInt(numbers.substring(i, i + 1)); + if (i % 2 == 0) { + res = n * 2; + } else { + res = n; + } + + calculatedNumbers += res; } - - private int calculateDigitSum(String numbers) { - int sum = 0; - for (int i = 0; i < numbers.length(); i++) { - int n = Integer.parseInt(numbers.substring(i, i + 1)); - sum += n; - } - return sum; + return calculatedNumbers; + } + + private int calculateDigitSum(String numbers) { + int sum = 0; + for (int i = 0; i < numbers.length(); i++) { + int n = Integer.parseInt(numbers.substring(i, i + 1)); + sum += n; } - + return sum; + } } diff --git a/src/main/java/org/thejavaguy/javafaker/service/FakeValues.java b/src/main/java/org/thejavaguy/javafaker/service/FakeValues.java index 05be841..5100bae 100644 --- a/src/main/java/org/thejavaguy/javafaker/service/FakeValues.java +++ b/src/main/java/org/thejavaguy/javafaker/service/FakeValues.java @@ -6,93 +6,92 @@ import java.util.List; import java.util.Locale; import java.util.Map; - import org.yaml.snakeyaml.Yaml; public class FakeValues implements FakeValuesInterface { - private final Locale locale; - private final String filename; - private final String path; - private Map values; - - FakeValues(Locale locale) { - this(locale, getFilename(locale), getFilename(locale)); - } + private final Locale locale; + private final String filename; + private final String path; + private Map values; - private static String getFilename(Locale locale) { - final StringBuilder filename = new StringBuilder(language(locale)); - if (!locale.getCountry().isEmpty()) { - filename.append("-").append(locale.getCountry()); - } - return filename.toString(); - } + FakeValues(Locale locale) { + this(locale, getFilename(locale), getFilename(locale)); + } - /** - * If you new up a locale with "he", it gets converted to "iw" which is old. - * This addresses that unfortunate condition. - */ - private static String language(Locale l) { - if (l.getLanguage().equals("iw")) { - return "he"; - } - return l.getLanguage(); + private static String getFilename(Locale locale) { + final StringBuilder filename = new StringBuilder(language(locale)); + if (!locale.getCountry().isEmpty()) { + filename.append("-").append(locale.getCountry()); } + return filename.toString(); + } - FakeValues(Locale locale, String filename, String path) { - this.locale = locale; - this.filename = filename; - this.path = path; + /** + * If you new up a locale with "he", it gets converted to "iw" which is old. This addresses that + * unfortunate condition. + */ + private static String language(Locale l) { + if (l.getLanguage().equals("iw")) { + return "he"; } + return l.getLanguage(); + } - @Override - public Map get(String key) { - if (values == null) { - values = loadValues(); - } + FakeValues(Locale locale, String filename, String path) { + this.locale = locale; + this.filename = filename; + this.path = path; + } - return values == null ? null : (Map) values.get(key); + @Override + public Map get(String key) { + if (values == null) { + values = loadValues(); } - private Map loadValues() { - String pathWithLocaleAndFilename = "/" + locale.getLanguage() + "/" + this.filename; - String pathWithFilename = "/" + filename + ".yml"; - String pathWithLocale = "/" + locale.getLanguage() + ".yml"; + return values == null ? null : (Map) values.get(key); + } - List paths = Arrays.asList(pathWithLocaleAndFilename, pathWithFilename, pathWithLocale); - InputStream stream = null; - for (String path : paths) { - stream = findStream(path); - if (stream != null) { - break; - } - } + private Map loadValues() { + String pathWithLocaleAndFilename = "/" + locale.getLanguage() + "/" + this.filename; + String pathWithFilename = "/" + filename + ".yml"; + String pathWithLocale = "/" + locale.getLanguage() + ".yml"; - if (stream == null) { - return null; - } + List paths = Arrays.asList(pathWithLocaleAndFilename, pathWithFilename, pathWithLocale); + InputStream stream = null; + for (String path : paths) { + stream = findStream(path); + if (stream != null) { + break; + } + } - final Map valuesMap = new Yaml().loadAs(stream, Map.class); - Map localeBased = (Map) valuesMap.get(locale.getLanguage()); - if (localeBased == null) { - localeBased = (Map) valuesMap.get(filename); - } - try { - stream.close(); - } catch (IOException ex){ - return null; - } - return (Map) localeBased.get("faker"); + if (stream == null) { + return null; } - private InputStream findStream(String filename) { - InputStream streamOnClass = getClass().getResourceAsStream(filename); - if (streamOnClass != null) { - return streamOnClass; - } - return getClass().getClassLoader().getResourceAsStream(filename); + final Map valuesMap = new Yaml().loadAs(stream, Map.class); + Map localeBased = (Map) valuesMap.get(locale.getLanguage()); + if (localeBased == null) { + localeBased = (Map) valuesMap.get(filename); + } + try { + stream.close(); + } catch (IOException ex) { + return null; } + return (Map) localeBased.get("faker"); + } - boolean supportsPath(String path) { - return this.path.equals(path); + private InputStream findStream(String filename) { + InputStream streamOnClass = getClass().getResourceAsStream(filename); + if (streamOnClass != null) { + return streamOnClass; } + return getClass().getClassLoader().getResourceAsStream(filename); + } + + boolean supportsPath(String path) { + return this.path.equals(path); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/service/FakeValuesGrouping.java b/src/main/java/org/thejavaguy/javafaker/service/FakeValuesGrouping.java index c8493fb..0a9e892 100644 --- a/src/main/java/org/thejavaguy/javafaker/service/FakeValuesGrouping.java +++ b/src/main/java/org/thejavaguy/javafaker/service/FakeValuesGrouping.java @@ -6,25 +6,25 @@ public class FakeValuesGrouping implements FakeValuesInterface { - private List fakeValuesList = new ArrayList<>(); + private List fakeValuesList = new ArrayList<>(); - public void add(FakeValues fakeValues) { - fakeValuesList.add(fakeValues); - } + public void add(FakeValues fakeValues) { + fakeValuesList.add(fakeValues); + } - @Override - public Map get(String key) { - Map result = null; - for (FakeValues fakeValues : fakeValuesList) { - if (fakeValues.supportsPath(key)) { - if (result != null) { - final Map newResult = fakeValues.get(key); - result.putAll(newResult); - } else { - result = fakeValues.get(key); - } - } + @Override + public Map get(String key) { + Map result = null; + for (FakeValues fakeValues : fakeValuesList) { + if (fakeValues.supportsPath(key)) { + if (result != null) { + final Map newResult = fakeValues.get(key); + result.putAll(newResult); + } else { + result = fakeValues.get(key); } - return result; + } } + return result; + } } diff --git a/src/main/java/org/thejavaguy/javafaker/service/FakeValuesInterface.java b/src/main/java/org/thejavaguy/javafaker/service/FakeValuesInterface.java index 90f3ade..89ab659 100644 --- a/src/main/java/org/thejavaguy/javafaker/service/FakeValuesInterface.java +++ b/src/main/java/org/thejavaguy/javafaker/service/FakeValuesInterface.java @@ -3,5 +3,5 @@ import java.util.Map; public interface FakeValuesInterface { - Map get(String key); + Map get(String key); } diff --git a/src/main/java/org/thejavaguy/javafaker/service/FakeValuesService.java b/src/main/java/org/thejavaguy/javafaker/service/FakeValuesService.java index ad19f70..3e94c5b 100644 --- a/src/main/java/org/thejavaguy/javafaker/service/FakeValuesService.java +++ b/src/main/java/org/thejavaguy/javafaker/service/FakeValuesService.java @@ -1,5 +1,6 @@ package org.thejavaguy.javafaker.service; +import com.mifmif.common.regex.Generex; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -12,591 +13,606 @@ import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; - import org.apache.commons.lang3.ClassUtils; import org.apache.commons.lang3.Strings; - import org.thejavaguy.javafaker.Address; import org.thejavaguy.javafaker.Faker; import org.thejavaguy.javafaker.Name; import org.thejavaguy.javafaker.service.files.EnFile; -import com.mifmif.common.regex.Generex; public class FakeValuesService { - private static final Pattern EXPRESSION_PATTERN = Pattern.compile("#\\{([a-z0-9A-Z_.]+)\\s?((?:,?'([^']+)')*)\\}"); - private static final Pattern EXPRESSION_ARGUMENTS_PATTERN = Pattern.compile("(?:'(.*?)')"); - - private final Logger log = Logger.getLogger("faker"); - - private final List fakeValuesList; - private final RandomService randomService; - - /** - *

- * Resolves YAML file using the most specific path first based on language and country code. - * 'en_US' would resolve in the following order: - *

    - *
  1. /en-US.yml
  2. - *
  3. /en.yml
  4. - *
- * The search is case-insensitive, so the following will all resolve correctly. Also, either a hyphen or - * an underscore can be used when constructing a {@link Locale} instance. This is legacy behavior and not - * condoned, but it will work. - *
    - *
  • EN_US
  • - *
  • En-Us
  • - *
  • eN_uS
  • - *
- *

- * - * @param locale - * @param randomService - */ - @SuppressWarnings({"unchecked", "rawtypes"}) - public FakeValuesService(Locale locale, RandomService randomService) { - if (locale == null) { - throw new IllegalArgumentException("locale is required"); - } - this.randomService = randomService; - locale = normalizeLocale(locale); - - final List locales = localeChain(locale); - final List all = new ArrayList(locales.size()); - - for (final Locale l : locales) { - boolean isEnglish = l.equals(Locale.ENGLISH); - if (isEnglish) { - FakeValuesGrouping fakeValuesGrouping = new FakeValuesGrouping(); - for (EnFile file : EnFile.getFiles()) { - fakeValuesGrouping.add(new FakeValues(l, file.getFile(), file.getPath())); - } - all.add(fakeValuesGrouping); - } else { - all.add(new FakeValues(l)); - } - } - - this.fakeValuesList = Collections.unmodifiableList(all); + private static final Pattern EXPRESSION_PATTERN = + Pattern.compile("#\\{([a-z0-9A-Z_.]+)\\s?((?:,?'([^']+)')*)\\}"); + private static final Pattern EXPRESSION_ARGUMENTS_PATTERN = Pattern.compile("(?:'(.*?)')"); + + private final Logger log = Logger.getLogger("faker"); + + private final List fakeValuesList; + private final RandomService randomService; + + /** + * Resolves YAML file using the most specific path first based on language and country code. + * 'en_US' would resolve in the following order: + * + *
    + *
  1. /en-US.yml + *
  2. /en.yml + *
+ * + * The search is case-insensitive, so the following will all resolve correctly. Also, either a + * hyphen or an underscore can be used when constructing a {@link Locale} instance. This is legacy + * behavior and not condoned, but it will work. + * + *
    + *
  • EN_US + *
  • En-Us + *
  • eN_uS + *
+ * + * @param locale + * @param randomService + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + public FakeValuesService(Locale locale, RandomService randomService) { + if (locale == null) { + throw new IllegalArgumentException("locale is required"); } - - /** - * Convert the specified locale into a chain of locales used for message resolution. For example: - *

- * {@link Locale#FRANCE} (fr_FR) -> [ fr_FR, anotherTest, en ] - * - * @return a list of {@link Locale} instances - */ - protected List localeChain(Locale from) { - if (Locale.ENGLISH.equals(from)) { - return Collections.singletonList(Locale.ENGLISH); + this.randomService = randomService; + locale = normalizeLocale(locale); + + final List locales = localeChain(locale); + final List all = new ArrayList(locales.size()); + + for (final Locale l : locales) { + boolean isEnglish = l.equals(Locale.ENGLISH); + if (isEnglish) { + FakeValuesGrouping fakeValuesGrouping = new FakeValuesGrouping(); + for (EnFile file : EnFile.getFiles()) { + fakeValuesGrouping.add(new FakeValues(l, file.getFile(), file.getPath())); } - - final Locale normalized = normalizeLocale(from); - - final List chain = new ArrayList<>(3); - chain.add(normalized); - if (!normalized.getCountry().isEmpty() && !Locale.ENGLISH.getLanguage().equals(normalized.getLanguage())) { - chain.add(new Locale(normalized.getLanguage())); - } - chain.add(Locale.ENGLISH); // default - return chain; + all.add(fakeValuesGrouping); + } else { + all.add(new FakeValues(l)); + } } - /** - * @return a proper {@link Locale} instance with language and country code set regardless of how - * it was instantiated. new Locale("pt-br") will be normalized to a locale constructed - * with new Locale("pt","BR"). - */ - private Locale normalizeLocale(Locale locale) { - final String[] parts = locale.toString().split("[-_]"); - - if (parts.length == 1) { - return new Locale(parts[0]); - } else { - return new Locale(parts[0], parts[1]); - } + this.fakeValuesList = Collections.unmodifiableList(all); + } + + /** + * Convert the specified locale into a chain of locales used for message resolution. For example: + * + *

{@link Locale#FRANCE} (fr_FR) -> [ fr_FR, anotherTest, en ] + * + * @return a list of {@link Locale} instances + */ + protected List localeChain(Locale from) { + if (Locale.ENGLISH.equals(from)) { + return Collections.singletonList(Locale.ENGLISH); } - /** - * Fetch a random value from an array item specified by the key - * - * @param key - * @return - */ - public Object fetch(String key) { - List valuesArray = (List) fetchObject(key); - return valuesArray == null ? null : valuesArray.get(randomService.nextInt(valuesArray.size())); - } + final Locale normalized = normalizeLocale(from); - /** - * Same as {@link #fetch(String)} except this casts the result into a String. - * - * @param key - * @return - */ - public String fetchString(String key) { - return (String) fetch(key); + final List chain = new ArrayList<>(3); + chain.add(normalized); + if (!normalized.getCountry().isEmpty() + && !Locale.ENGLISH.getLanguage().equals(normalized.getLanguage())) { + chain.add(new Locale(normalized.getLanguage())); } - - /** - * Safely fetches a key. - *

- * If the value is null, it will return an empty string. - *

- * If it is a list, it will assume it is a list of strings and select a random value from it. - *

- * If the retrieved value is an slash encoded regular expression such as {@code /[a-b]/} then - * the regex will be converted to a regexify expression and returned (ex. {@code #regexify '[a-b]'}) - *

- * Otherwise it will just return the value as a string. - * - * @param key the key to fetch from the YML structure. - * @param defaultIfNull the value to return if the fetched value is null - * @return see above - */ - @SuppressWarnings("unchecked") - public String safeFetch(String key, String defaultIfNull) { - Object o = fetchObject(key); - if (o == null) return defaultIfNull; - if (o instanceof List) { - List values = (List) o; - if (values.isEmpty()) { - return defaultIfNull; - } - return values.get(randomService.nextInt(values.size())); - } else if (isSlashDelimitedRegex(o.toString())) { - return String.format("#{regexify '%s'}", trimRegexSlashes(o.toString())); - } else { - return (String) o; - } + chain.add(Locale.ENGLISH); // default + return chain; + } + + /** + * @return a proper {@link Locale} instance with language and country code set regardless of how + * it was instantiated. new Locale("pt-br") will be normalized to a locale constructed with + * new Locale("pt","BR"). + */ + private Locale normalizeLocale(Locale locale) { + final String[] parts = locale.toString().split("[-_]"); + + if (parts.length == 1) { + return new Locale(parts[0]); + } else { + return new Locale(parts[0], parts[1]); } - - /** - * Return the object selected by the key from yaml file. - * - * @param key key contains path to an object. Path segment is separated by - * dot. E.g. name.first_name - * @return - */ - public Object fetchObject(String key) { - String[] path = key.split("\\."); - - Object result = null; - for (FakeValuesInterface fakeValuesInterface : fakeValuesList) { - Object currentValue = fakeValuesInterface; - for (int p = 0; currentValue != null && p < path.length; p++) { - String currentPath = path[p]; - if (currentValue instanceof Map) { - currentValue = ((Map) currentValue).get(currentPath); - } else { - currentValue = ((FakeValuesInterface) currentValue).get(currentPath); - } - } - result = currentValue; - if (result != null) { - break; - } - } - return result; + } + + /** + * Fetch a random value from an array item specified by the key + * + * @param key + * @return + */ + public Object fetch(String key) { + List valuesArray = (List) fetchObject(key); + return valuesArray == null ? null : valuesArray.get(randomService.nextInt(valuesArray.size())); + } + + /** + * Same as {@link #fetch(String)} except this casts the result into a String. + * + * @param key + * @return + */ + public String fetchString(String key) { + return (String) fetch(key); + } + + /** + * Safely fetches a key. + * + *

If the value is null, it will return an empty string. + * + *

If it is a list, it will assume it is a list of strings and select a random value from it. + * + *

If the retrieved value is an slash encoded regular expression such as {@code /[a-b]/} then + * the regex will be converted to a regexify expression and returned (ex. {@code #regexify + * '[a-b]'}) + * + *

Otherwise it will just return the value as a string. + * + * @param key the key to fetch from the YML structure. + * @param defaultIfNull the value to return if the fetched value is null + * @return see above + */ + @SuppressWarnings("unchecked") + public String safeFetch(String key, String defaultIfNull) { + Object o = fetchObject(key); + if (o == null) return defaultIfNull; + if (o instanceof List) { + List values = (List) o; + if (values.isEmpty()) { + return defaultIfNull; + } + return values.get(randomService.nextInt(values.size())); + } else if (isSlashDelimitedRegex(o.toString())) { + return String.format("#{regexify '%s'}", trimRegexSlashes(o.toString())); + } else { + return (String) o; } - - /** - * Returns a string with the '#' characters in the parameter replaced with random digits between 0-9 inclusive. - *

- * For example, the string "ABC##EFG" could be replaced with a string like "ABC99EFG". - * - * @param numberString - * @return - */ - public String numerify(String numberString) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < numberString.length(); i++) { - if (numberString.charAt(i) == '#') { - sb.append(randomService.nextInt(10)); - } else { - sb.append(numberString.charAt(i)); - } + } + + /** + * Return the object selected by the key from yaml file. + * + * @param key key contains path to an object. Path segment is separated by dot. E.g. + * name.first_name + * @return + */ + public Object fetchObject(String key) { + String[] path = key.split("\\."); + + Object result = null; + for (FakeValuesInterface fakeValuesInterface : fakeValuesList) { + Object currentValue = fakeValuesInterface; + for (int p = 0; currentValue != null && p < path.length; p++) { + String currentPath = path[p]; + if (currentValue instanceof Map) { + currentValue = ((Map) currentValue).get(currentPath); + } else { + currentValue = ((FakeValuesInterface) currentValue).get(currentPath); } - - return sb.toString(); - } - - /** - * Applies both a {@link #numerify(String)} and a {@link #letterify(String)} - * over the incoming string. - * - * @param string - * @return - */ - public String bothify(String string) { - return letterify(numerify(string)); + } + result = currentValue; + if (result != null) { + break; + } } - - /** - * Applies both a {@link #numerify(String)} and a {@link #letterify(String, boolean)} - * over the incoming string. - * - * @param string - * @param isUpper - * @return - */ - public String bothify(String string, boolean isUpper) { - return letterify(numerify(string), isUpper); + return result; + } + + /** + * Returns a string with the '#' characters in the parameter replaced with random digits between + * 0-9 inclusive. + * + *

For example, the string "ABC##EFG" could be replaced with a string like "ABC99EFG". + * + * @param numberString + * @return + */ + public String numerify(String numberString) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < numberString.length(); i++) { + if (numberString.charAt(i) == '#') { + sb.append(randomService.nextInt(10)); + } else { + sb.append(numberString.charAt(i)); + } } - /** - * Generates a String that matches the given regular expression. - */ - public String regexify(String regex) { - Generex generex = new Generex(regex); - generex.setSeed(randomService.nextLong()); - return generex.random(); + return sb.toString(); + } + + /** + * Applies both a {@link #numerify(String)} and a {@link #letterify(String)} over the incoming + * string. + * + * @param string + * @return + */ + public String bothify(String string) { + return letterify(numerify(string)); + } + + /** + * Applies both a {@link #numerify(String)} and a {@link #letterify(String, boolean)} over the + * incoming string. + * + * @param string + * @param isUpper + * @return + */ + public String bothify(String string, boolean isUpper) { + return letterify(numerify(string), isUpper); + } + + /** Generates a String that matches the given regular expression. */ + public String regexify(String regex) { + Generex generex = new Generex(regex); + generex.setSeed(randomService.nextLong()); + return generex.random(); + } + + /** + * Returns a string with the '?' characters in the parameter replaced with random alphabetic + * characters. + * + *

For example, the string "12??34" could be replaced with a string like "12AB34". + * + * @param letterString + * @return + */ + public String letterify(String letterString) { + return this.letterify(letterString, false); + } + + /** + * Returns a string with the '?' characters in the parameter replaced with random alphabetic + * characters. + * + *

For example, the string "12??34" could be replaced with a string like "12AB34". + * + * @param letterString + * @param isUpper specifies whether or not letters should be upper case + * @return + */ + public String letterify(String letterString, boolean isUpper) { + return letterHelper((isUpper) ? 65 : 97, letterString); // from ascii table + } + + private String letterHelper(int baseChar, String letterString) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < letterString.length(); i++) { + if (letterString.charAt(i) == '?') { + sb.append((char) (baseChar + randomService.nextInt(26))); // a-z + } else { + sb.append(letterString.charAt(i)); + } } - /** - * Returns a string with the '?' characters in the parameter replaced with random alphabetic - * characters. - *

- * For example, the string "12??34" could be replaced with a string like "12AB34". - * - * @param letterString - * @return - */ - public String letterify(String letterString) { - return this.letterify(letterString, false); + return sb.toString(); + } + + /** + * Resolves a key to a method on an object. + * + *

#{hello} with result in a method call to current.hello(); + * + *

#{Person.hello_someone} will result in a method call to person.helloSomeone(); + */ + public String resolve(String key, Object current, Faker root) { + final String expression = safeFetch(key, null); + + if (expression == null) { + throw new RuntimeException(key + " resulted in null expression"); } - /** - * Returns a string with the '?' characters in the parameter replaced with random alphabetic - * characters. - *

- * For example, the string "12??34" could be replaced with a string like "12AB34". - * - * @param letterString - * @param isUpper specifies whether or not letters should be upper case - * @return - */ - public String letterify(String letterString, boolean isUpper) { - return letterHelper((isUpper) ? 65 : 97, letterString); // from ascii table - } - - private String letterHelper(int baseChar, String letterString) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < letterString.length(); i++) { - if (letterString.charAt(i) == '?') { - sb.append((char) (baseChar + randomService.nextInt(26))); // a-z - } else { - sb.append(letterString.charAt(i)); - } - } - - return sb.toString(); - } - - /** - * Resolves a key to a method on an object. - *

- * #{hello} with result in a method call to current.hello(); - *

- * #{Person.hello_someone} will result in a method call to person.helloSomeone(); - */ - public String resolve(String key, Object current, Faker root) { - final String expression = safeFetch(key, null); - - if (expression == null) { - throw new RuntimeException(key + " resulted in null expression"); - } - - return resolveExpression(expression, current, root); + return resolveExpression(expression, current, root); + } + + /** + * resolves an expression using the current faker. + * + * @param expression + * @param faker + * @return + */ + public String expression(String expression, Faker faker) { + return resolveExpression(expression, null, faker); + } + + /** + * processes a expression in the style #{X.y} using the current objects as the 'current' location + * within the yml file (or the {@link Faker} object hierarchy as it were). + * + *

#{Address.streetName} would get resolved to {@link Faker#address()}'s {@link + * Address#streetName()} + * + *

#{address.street} would get resolved to the YAML > locale: faker: address: street: + * + *

Combinations are supported as well: "#{x} #{y}" + * + *

Recursive templates are supported. if "#{x}" resolves to "#{Address.streetName}" then "#{x}" + * resolves to {@link Faker#address()}'s {@link Address#streetName()}. + */ + protected String resolveExpression(String expression, Object current, Faker root) { + final Matcher matcher = EXPRESSION_PATTERN.matcher(expression); + + String result = expression; + while (matcher.find()) { + final String escapedDirective = matcher.group(0); + final String directive = matcher.group(1); + final String arguments = matcher.group(2); + final Matcher argsMatcher = EXPRESSION_ARGUMENTS_PATTERN.matcher(arguments); + List args = new ArrayList<>(); + while (argsMatcher.find()) { + args.add(argsMatcher.group(1)); + } + + // resolve the expression and reprocess it to handle recursive templates + String resolved = resolveExpression(directive, args, current, root); + if (resolved == null) { + throw new RuntimeException("Unable to resolve " + escapedDirective + " directive."); + } + + resolved = resolveExpression(resolved, current, root); + result = Strings.CS.replaceOnce(result, escapedDirective, resolved); } - - /** - * resolves an expression using the current faker. - * - * @param expression - * @param faker - * @return - */ - public String expression(String expression, Faker faker) { - return resolveExpression(expression, null, faker); + return result; + } + + /** + * + * + *

Search Order

+ * + *
    + *
  • Search for methods on the current object + *
  • local keys in Yaml File + *
  • Search for methods on faker child objects + *
  • Search for keys in yaml file by transforming object reference to yaml reference + *
+ * + * @return null if unable to resolve + */ + private String resolveExpression( + String directive, List args, Object current, Faker root) { + // name.name (resolve locally) + // Name.first_name (resolve to faker.name().firstName()) + final String simpleDirective = + (isDotDirective(directive) || current == null) + ? directive + : classNameToYamlName(current) + "." + directive; + + String resolved = null; + // resolve method references on CURRENT object like #{number_between '1','10'} on Number or + // #{ssn_valid} on IdNumber + if (!isDotDirective(directive)) { + resolved = resolveFromMethodOn(current, directive, args); } - /** - *

processes a expression in the style #{X.y} using the current objects as the 'current' location - * within the yml file (or the {@link Faker} object hierarchy as it were). - *

- *

- * #{Address.streetName} would get resolved to {@link Faker#address()}'s {@link Address#streetName()} - *

- *

- * #{address.street} would get resolved to the YAML > locale: faker: address: street: - *

- *

- * Combinations are supported as well: "#{x} #{y}" - *

- *

- * Recursive templates are supported. if "#{x}" resolves to "#{Address.streetName}" then "#{x}" resolves to - * {@link Faker#address()}'s {@link Address#streetName()}. - *

- */ - protected String resolveExpression(String expression, Object current, Faker root) { - final Matcher matcher = EXPRESSION_PATTERN.matcher(expression); - - String result = expression; - while (matcher.find()) { - final String escapedDirective = matcher.group(0); - final String directive = matcher.group(1); - final String arguments = matcher.group(2); - final Matcher argsMatcher = EXPRESSION_ARGUMENTS_PATTERN.matcher(arguments); - List args = new ArrayList<>(); - while (argsMatcher.find()) { - args.add(argsMatcher.group(1)); - } - - // resolve the expression and reprocess it to handle recursive templates - String resolved = resolveExpression(directive, args, current, root); - if (resolved == null) { - throw new RuntimeException("Unable to resolve " + escapedDirective + " directive."); - } - - resolved = resolveExpression(resolved, current, root); - result = Strings.CS.replaceOnce(result, escapedDirective, resolved); - } - return result; + // simple fetch of a value from the yaml file. the directive may have been mutated + // such that if the current yml object is car: and directive is #{wheel} then + // car.wheel will be looked up in the YAML file. + if (resolved == null) { + resolved = safeFetch(simpleDirective, null); } - /** - *

Search Order

- *
    - *
  • Search for methods on the current object
  • - *
  • local keys in Yaml File
  • - *
  • Search for methods on faker child objects
  • - *
  • Search for keys in yaml file by transforming object reference to yaml reference
  • - *
- * - * @return null if unable to resolve - */ - private String resolveExpression(String directive, List args, Object current, Faker root) { - // name.name (resolve locally) - // Name.first_name (resolve to faker.name().firstName()) - final String simpleDirective = (isDotDirective(directive) || current == null) - ? directive - : classNameToYamlName(current) + "." + directive; - - String resolved = null; - // resolve method references on CURRENT object like #{number_between '1','10'} on Number or - // #{ssn_valid} on IdNumber - if (!isDotDirective(directive)) { - resolved = resolveFromMethodOn(current, directive, args); - } - - // simple fetch of a value from the yaml file. the directive may have been mutated - // such that if the current yml object is car: and directive is #{wheel} then - // car.wheel will be looked up in the YAML file. - if (resolved == null) { - resolved = safeFetch(simpleDirective, null); - } - - // resolve method references on faker object like #{regexify '[a-z]'} - if (resolved == null && !isDotDirective(directive)) { - resolved = resolveFromMethodOn(root, directive, args); - } - - // Resolve Faker Object method references like #{ClassName.method_name} - if (resolved == null && isDotDirective(directive)) { - resolved = resolveFakerObjectAndMethod(root, directive, args); - } - - // last ditch effort. Due to Ruby's dynamic nature, something like 'Address.street_title' will resolve - // because 'street_title' is a dynamic method on the Address object. We can't do this in Java so we go - // thru the normal resolution above, but if we will can't resolve it, we once again do a 'safeFetch' as we - // did first but FIRST we change the Object reference Class.method_name with a yml style internal refernce -> - // class.method_name (lowercase) - if (resolved == null && isDotDirective(directive)) { - resolved = safeFetch(javaNameToYamlName(simpleDirective), null); - } - - return resolved; + // resolve method references on faker object like #{regexify '[a-z]'} + if (resolved == null && !isDotDirective(directive)) { + resolved = resolveFromMethodOn(root, directive, args); } - - /** - * @param expression input expression - * @return true if s is non null and is a slash delimited regex (ex. {@code /[ab]/}) - */ - private boolean isSlashDelimitedRegex(String expression) { - return expression != null && expression.startsWith("/") && expression.endsWith("/"); + // Resolve Faker Object method references like #{ClassName.method_name} + if (resolved == null && isDotDirective(directive)) { + resolved = resolveFakerObjectAndMethod(root, directive, args); } - /** - * Given a {@code slashDelimitedRegex} such as {@code /[ab]/}, removes the slashes and returns only {@code [ab]} - * - * @param slashDelimitedRegex a non null slash delimited regex (ex. {@code /[ab]/}) - * @return the regex without the slashes (ex. {@code [ab]}) - */ - private String trimRegexSlashes(String slashDelimitedRegex) { - return slashDelimitedRegex.substring(1, slashDelimitedRegex.length() - 1); + // last ditch effort. Due to Ruby's dynamic nature, something like 'Address.street_title' will + // resolve + // because 'street_title' is a dynamic method on the Address object. We can't do this in Java + // so we go + // thru the normal resolution above, but if we will can't resolve it, we once again do a + // 'safeFetch' as we + // did first but FIRST we change the Object reference Class.method_name with a yml style + // internal refernce -> + // class.method_name (lowercase) + if (resolved == null && isDotDirective(directive)) { + resolved = safeFetch(javaNameToYamlName(simpleDirective), null); } - private boolean isDotDirective(String directive) { - return directive.contains("."); + return resolved; + } + + /** + * @param expression input expression + * @return true if s is non null and is a slash delimited regex (ex. {@code /[ab]/}) + */ + private boolean isSlashDelimitedRegex(String expression) { + return expression != null && expression.startsWith("/") && expression.endsWith("/"); + } + + /** + * Given a {@code slashDelimitedRegex} such as {@code /[ab]/}, removes the slashes and returns + * only {@code [ab]} + * + * @param slashDelimitedRegex a non null slash delimited regex (ex. {@code /[ab]/}) + * @return the regex without the slashes (ex. {@code [ab]}) + */ + private String trimRegexSlashes(String slashDelimitedRegex) { + return slashDelimitedRegex.substring(1, slashDelimitedRegex.length() - 1); + } + + private boolean isDotDirective(String directive) { + return directive.contains("."); + } + + /** + * @return a yaml style name from the classname of the supplied object (PhoneNumber => + * phone_number) + */ + private String classNameToYamlName(Object current) { + return javaNameToYamlName(current.getClass().getSimpleName()); + } + + /** + * @return a yaml style name like 'phone_number' from a java style name like 'PhoneNumber' + */ + private String javaNameToYamlName(String expression) { + return expression.replaceAll("([A-Z])", "_$1").substring(1).toLowerCase(); + } + + /** + * Given a directive like 'firstName', attempts to resolve it to a method. For example if obj is + * an instance of {@link Name} then this method would return {@link Name#firstName()}. Returns + * null if the directive is nested (i.e. has a '.') or the method doesn't exist on the + * obj object. + */ + private String resolveFromMethodOn(Object obj, String directive, List args) { + if (obj == null) { + return null; } - - /** - * @return a yaml style name from the classname of the supplied object (PhoneNumber => phone_number) - */ - private String classNameToYamlName(Object current) { - return javaNameToYamlName(current.getClass().getSimpleName()); + try { + final MethodAndCoercedArgs accessor = accessor(obj, directive, args); + return (accessor == null) ? null : string(accessor.invoke(obj)); + } catch (Exception e) { + log.log(Level.FINE, "Can't call " + directive + " on " + obj, e); + return null; } - - /** - * @return a yaml style name like 'phone_number' from a java style name like 'PhoneNumber' - */ - private String javaNameToYamlName(String expression) { - return expression.replaceAll("([A-Z])", "_$1") - .substring(1) - .toLowerCase(); + } + + /** + * Accepts a {@link Faker} instance and a name.firstName style 'key' which is resolved to the + * return value of: {@link Faker#name()}'s {@link Name#firstName()} method. + * + * @throws RuntimeException if there's a problem invoking the method or it doesn't exist. + */ + private String resolveFakerObjectAndMethod(Faker faker, String key, List args) { + final String[] classAndMethod = key.split("\\.", 2); + + try { + String fakerMethodName = classAndMethod[0].replaceAll("_", ""); + MethodAndCoercedArgs fakerAccessor = + accessor(faker, fakerMethodName, Collections.emptyList()); + if (fakerAccessor == null) { + log.fine("Can't find top level faker object named " + fakerMethodName + "."); + return null; + } + Object objectWithMethodToInvoke = fakerAccessor.invoke(faker); + String nestedMethodName = classAndMethod[1].replaceAll("_", ""); + final MethodAndCoercedArgs accessor = + accessor(objectWithMethodToInvoke, classAndMethod[1].replaceAll("_", ""), args); + if (accessor == null) { + throw new Exception( + "Can't find method on " + + objectWithMethodToInvoke.getClass().getSimpleName() + + " called " + + nestedMethodName + + "."); + } + + return string(accessor.invoke(objectWithMethodToInvoke)); + } catch (Exception e) { + log.fine(e.getMessage()); + return null; } - - - /** - * Given a directive like 'firstName', attempts to resolve it to a method. For example if obj is an instance of - * {@link Name} then this method would return {@link Name#firstName()}. Returns null if the directive is nested - * (i.e. has a '.') or the method doesn't exist on the obj object. - */ - private String resolveFromMethodOn(Object obj, String directive, List args) { - if (obj == null) { - return null; - } - try { - final MethodAndCoercedArgs accessor = accessor(obj, directive, args); - return (accessor == null) - ? null - : string(accessor.invoke(obj)); - } catch (Exception e) { - log.log(Level.FINE, "Can't call " + directive + " on " + obj, e); - return null; + } + + /** Find an accessor by name ignoring case. */ + private MethodAndCoercedArgs accessor(Object onObject, String name, List args) { + log.log( + Level.FINE, + "Find accessor named " + + name + + " on " + + onObject.getClass().getSimpleName() + + " with args " + + args); + + for (Method m : onObject.getClass().getMethods()) { + if (m.getName().equalsIgnoreCase(name) && m.getParameterTypes().length == args.size()) { + final List coercedArguments = coerceArguments(m, args); + if (coercedArguments != null) { + return new MethodAndCoercedArgs(m, coercedArguments); } + } } - /** - * Accepts a {@link Faker} instance and a name.firstName style 'key' which is resolved to the return value of: - * {@link Faker#name()}'s {@link Name#firstName()} method. - * - * @throws RuntimeException if there's a problem invoking the method or it doesn't exist. - */ - private String resolveFakerObjectAndMethod(Faker faker, String key, List args) { - final String[] classAndMethod = key.split("\\.", 2); - - try { - String fakerMethodName = classAndMethod[0].replaceAll("_", ""); - MethodAndCoercedArgs fakerAccessor = accessor(faker, fakerMethodName, Collections.emptyList()); - if (fakerAccessor == null) { - log.fine("Can't find top level faker object named " + fakerMethodName + "."); - return null; - } - Object objectWithMethodToInvoke = fakerAccessor.invoke(faker); - String nestedMethodName = classAndMethod[1].replaceAll("_", ""); - final MethodAndCoercedArgs accessor = accessor(objectWithMethodToInvoke, classAndMethod[1].replaceAll("_", ""), args); - if (accessor == null) { - throw new Exception("Can't find method on " - + objectWithMethodToInvoke.getClass().getSimpleName() - + " called " + nestedMethodName + "."); - } - - return string(accessor.invoke(objectWithMethodToInvoke)); - } catch (Exception e) { - log.fine(e.getMessage()); - return null; - } + if (name.contains("_")) { + return accessor(onObject, name.replaceAll("_", ""), args); } - - - /** - * Find an accessor by name ignoring case. - */ - private MethodAndCoercedArgs accessor(Object onObject, String name, List args) { - log.log(Level.FINE, "Find accessor named " + name + " on " + onObject.getClass().getSimpleName() + " with args " + args); - - for (Method m : onObject.getClass().getMethods()) { - if (m.getName().equalsIgnoreCase(name) - && m.getParameterTypes().length == args.size()) { - final List coercedArguments = coerceArguments(m, args); - if (coercedArguments != null) { - return new MethodAndCoercedArgs(m, coercedArguments); - } - } - } - - if (name.contains("_")) { - return accessor(onObject, name.replaceAll("_", ""), args); + return null; + } + + /** + * Coerce arguments in args into the appropriate types (if possible) for the parameter + * arguments to accessor. + * + * @return list of coerced values if successful, null otherwise + */ + private List coerceArguments(Method accessor, List args) { + final List coerced = new ArrayList<>(); + for (int i = 0; i < accessor.getParameterTypes().length; i++) { + + Class toType = ClassUtils.primitiveToWrapper(accessor.getParameterTypes()[i]); + try { + if (toType.isEnum()) { + Method method = toType.getMethod("valueOf", String.class); + String enumArg = args.get(i).substring(args.get(i).indexOf(".") + 1); + Object coercedArg = method.invoke(null, enumArg); + coerced.add(coercedArg); + } else { + final Constructor ctor = toType.getConstructor(String.class); + final Object coercedArgument = ctor.newInstance(args.get(i)); + coerced.add(coercedArgument); } + } catch (Exception e) { + log.fine( + "Unable to coerce " + + args.get(i) + + " to " + + toType.getSimpleName() + + " via " + + toType.getSimpleName() + + "(String) constructor."); return null; + } } + return coerced; + } - /** - * Coerce arguments in args into the appropriate types (if possible) for the parameter arguments - * to accessor. - * - * @return list of coerced values if successful, null otherwise - */ - private List coerceArguments(Method accessor, List args) { - final List coerced = new ArrayList<>(); - for (int i = 0; i < accessor.getParameterTypes().length; i++) { - - Class toType = ClassUtils.primitiveToWrapper(accessor.getParameterTypes()[i]); - try { - if (toType.isEnum()) { - Method method = toType.getMethod( "valueOf", String.class ); - String enumArg = args.get( i ).substring( args.get( i ).indexOf( "." ) + 1 ); - Object coercedArg = method.invoke( null, enumArg ); - coerced.add( coercedArg ); - } else { - final Constructor ctor = toType.getConstructor(String.class); - final Object coercedArgument = ctor.newInstance(args.get(i)); - coerced.add(coercedArgument); - } - } catch (Exception e) { - log.fine("Unable to coerce " + args.get(i) + " to " + toType.getSimpleName() + " via " + toType.getSimpleName() + "(String) constructor."); - return null; - } - } - return coerced; - } - - private String string(Object obj) { - return (obj == null) ? null : obj.toString(); - } + private String string(Object obj) { + return (obj == null) ? null : obj.toString(); + } - /** - * simple wrapper class around an accessor and a list of coerced arguments. - * this is useful as we get to find the method and coerce the arguments in one - * shot, returning both when successful. This saves us from doing it more than once (coercing args). - */ - private static class MethodAndCoercedArgs { + /** + * simple wrapper class around an accessor and a list of coerced arguments. this is useful as we + * get to find the method and coerce the arguments in one shot, returning both when successful. + * This saves us from doing it more than once (coercing args). + */ + private static class MethodAndCoercedArgs { - private final Method method; + private final Method method; - private final List coerced; + private final List coerced; - private MethodAndCoercedArgs(Method m, List coerced) { - this.method = requireNonNull(m, "method cannot be null"); - this.coerced = requireNonNull(coerced, "coerced arguments cannot be null"); - } + private MethodAndCoercedArgs(Method m, List coerced) { + this.method = requireNonNull(m, "method cannot be null"); + this.coerced = requireNonNull(coerced, "coerced arguments cannot be null"); + } - private Object invoke(Object on) throws InvocationTargetException, IllegalAccessException { - return method.invoke(on, coerced.toArray()); - } + private Object invoke(Object on) throws InvocationTargetException, IllegalAccessException { + return method.invoke(on, coerced.toArray()); + } - /** - * source level precludes me from using Objects.requireNonNull - */ - private T requireNonNull(T instance, String messageIfNull) { - if (instance == null) { - throw new NullPointerException(messageIfNull); - } - return instance; - } + /** source level precludes me from using Objects.requireNonNull */ + private T requireNonNull(T instance, String messageIfNull) { + if (instance == null) { + throw new NullPointerException(messageIfNull); + } + return instance; } + } } diff --git a/src/main/java/org/thejavaguy/javafaker/service/FakerIDN.java b/src/main/java/org/thejavaguy/javafaker/service/FakerIDN.java index d497558..689f060 100644 --- a/src/main/java/org/thejavaguy/javafaker/service/FakerIDN.java +++ b/src/main/java/org/thejavaguy/javafaker/service/FakerIDN.java @@ -2,31 +2,29 @@ import java.net.IDN; -/** - * Created by tshick on 10/30/16. - */ +/** Created by tshick on 10/30/16. */ public class FakerIDN { - /** - * {@link IDN#toASCII(String)} is too picky for our needs. It was throwing exceptions for fa.yml and - * he.yml as they're Bidi languages and something was causing them to die. This is kind of a brute force - * fix but it appears to fix the issue. - */ - public static String toASCII(String in) { - try { - return IDN.toASCII(in); - } catch (Exception e) { - // let's continue with the character by character encoding hack. - } - final StringBuilder sb = new StringBuilder(); - for (int i=0;i>> 1; + val = bits % n; + } while (bits - val + (n - 1) < 0L); + return val; + } - long bits, val; - do { - long randomLong = random.nextLong(); - bits = (randomLong << 1) >>> 1; - val = bits % n; - } while (bits - val + (n - 1) < 0L); - return val; - } + public double nextDouble() { + return random.nextDouble(); + } - public double nextDouble() { - return random.nextDouble(); - } + public Boolean nextBoolean() { + return random.nextBoolean(); + } - public Boolean nextBoolean() { - return random.nextBoolean(); - } + public Integer nextInt(int min, int max) { + return random.nextInt((max - min) + 1) + min; + } - public Integer nextInt(int min, int max) { - return random.nextInt((max - min) + 1) + min; - } + public String hex() { + return hex(8); + } - public String hex() { - return hex(8); + public String hex(int length) { + if (length <= 0) { + return ""; // Keep the existing behavior instead of throwing an error. } - - public String hex(int length) { - if (length <= 0) { - return ""; // Keep the existing behavior instead of throwing an error. - } - final char[] hexChars = new char[length]; - for (int i = 0; i < length; i++) { - final int nextHex = nextInt(16); - if (nextHex < 10) { - hexChars[i] = (char) ('0' + nextHex); - } else { - hexChars[i] = (char) ('A' + nextHex - 10); - } - } - return new String(hexChars); + final char[] hexChars = new char[length]; + for (int i = 0; i < length; i++) { + final int nextHex = nextInt(16); + if (nextHex < 10) { + hexChars[i] = (char) ('0' + nextHex); + } else { + hexChars[i] = (char) ('A' + nextHex - 10); + } } + return new String(hexChars); + } } diff --git a/src/main/java/org/thejavaguy/javafaker/service/files/EnFile.java b/src/main/java/org/thejavaguy/javafaker/service/files/EnFile.java index dc74bde..543d1ef 100644 --- a/src/main/java/org/thejavaguy/javafaker/service/files/EnFile.java +++ b/src/main/java/org/thejavaguy/javafaker/service/files/EnFile.java @@ -5,208 +5,210 @@ import java.util.List; public class EnFile { - private final String file; - private final String path; - - private EnFile(String file) { - this(file, file.replaceFirst(".yml", "")); - } - - private EnFile(String file, String path) { - this.file = file; - this.path = path; - } + private final String file; + private final String path; + private EnFile(String file) { + this(file, file.replaceFirst(".yml", "")); + } - public String getFile() { - return file; - } - - public String getPath() { - return path; - } + private EnFile(String file, String path) { + this.file = file; + this.path = path; + } - private static List FILES = Arrays.asList("address.yml", - "ancient.yml", - "animal.yml", - "app.yml", - "appliance.yml", - "aqua_teen_hunger_force.yml", - "artist.yml", - "aviation.yml", - "back_to_the_future.yml", - "barcode.yml", - "bank.yml", - "basketball.yml", - "beer.yml", - "bojack_horseman.yml", - "book.yml", - "bossa_nova.yml", - "breaking_bad.yml", - "buffy.yml", - "business.yml", - "cannabis.yml", - "chuck_norris.yml", - "code.yml", - "coffee.yml", - "coin.yml", - "color.yml", - "commerce.yml", - "community.yml", - "company.yml", - "credit_card.yml", - "compass.yml", - "construction.yml", - "cosmere.yml", - "country.yml", - "crypto_coin.yml", - "currency.yml", - "dc_comics.yml", - "demographic.yml", - "dessert.yml", - "device.yml", - "disease.yml", - "dota.yml", - "dr_who.yml", - "dragon_ball.yml", - "dumb_and_dumber.yml", - "dune.yml", - "educator.yml", - "elder_scrolls.yml", - "electrical_components.yml", - "esport.yml", - "englandfootball.yml", - "fallout.yml", - "family_guy.yml", - "famous_last_words.yml", - "file.yml", - "finance.yml", - "food.yml", - "football.yml", - "fresh_prince_of_bel_air.yml", - "friends.yml", - "funny_name.yml", - "game_of_thrones.yml", - "gender.yml", - "ghostbusters.yml", - "grateful_dead.yml", - "greek_philosophers.yml", - "hacker.yml", - "half_life.yml", - "harry_potter.yml", - "heroes.yml", - "heroes_of_the_storm.yml", - "hey_arnold.yml", - "hipster.yml", - "hitchhikers_guide_to_the_galaxy.yml", - "hobbit.yml", - "house.yml", - "how_i_met_your_mother.yml", - "id_number.yml", - "industry_segments.yml", - "internet.yml", - "invoice.yml", - "job.yml", - "kpop.yml", - "lebowski.yml", - "lord_of_the_rings.yml", - "lorem.yml", - "lovecraft.yml", - "markdown.yml", - "marketing.yml", - "matz.yml", - "measurement.yml", - "medical.yml", - "michael_scott.yml", - "military.yml", - "most_interesting_man_in_the_world.yml", - "movie.yml", - "mountain.yml", - "music.yml", - "myst.yml", - "name.yml", - "nation.yml", - "nato_phonetic_alphabet.yml", - "new_girl.yml", - "one_piece.yml", - "overwatch.yml", - "parks_and_rec.yml", - "phish.yml", - "phone_number.yml", - "photography.yml", - "pokemon.yml", - "princess_bride.yml", - "programming_language.yml", - "relationship.yml", - "restaurant.yml", - "rick_and_morty.yml", - "robin.yml", - "rock_band.yml", - "rupaul.yml", - "science.yml", - "seinfeld.yml", - "shakespeare.yml", - "shipping.yml", - "silicon_valley.yml", - "simpsons.yml", - "singular_siegler.yml", - "sip.yml", - "slack_emoji.yml", - "sonic_the_hedgehog.yml", - "source.yml", - "south_park.yml", - "space.yml", - "starcraft.yml", - "star_trek.yml", - "star_wars.yml", - "stargate.yml", - "stock.yml", - "stranger_thing.yml", - "stripe.yml", - "subscription.yml", - "super_smash_bros.yml", - "superhero.yml", - "sword_art_online.yml", - "team.yml", - "the_expanse.yml", - "the_it_crowd.yml", - "the_thick_of_it.yml", - "twin_peaks.yml", - "umphreys_mcgee.yml", - "university.yml", - "v_for_vendetta.yml", - "vehicle.yml", - "venture_bros.yml", - "verbs.yml", - "weather.yml", - "witcher.yml", - "kaamelott.yml", - "world_cup.yml", - "world_of_warcraft.yml", - "yoda.yml", - "zelda.yml"); + public String getFile() { + return file; + } - // files where the search path can't be derived from the filename - private static List FILES_WITH_A_DIFFERENT_PATH = Arrays.asList( - new EnFile("animal.yml", "creature"), - new EnFile("cat.yml", "creature"), - new EnFile("dog.yml", "creature"), - new EnFile("league_of_legends.yml", "games"), - new EnFile("overwatch.yml", "games"), - new EnFile("pokemon.yml", "games"), - new EnFile("witcher.yml", "games"), - new EnFile("zelda.yml", "games"), - new EnFile("elder_scrolls.yml", "games"), - new EnFile("phone_number.yml", "cell_phone")); // load phone number again with a differen path + public String getPath() { + return path; + } + private static List FILES = + Arrays.asList( + "address.yml", + "ancient.yml", + "animal.yml", + "app.yml", + "appliance.yml", + "aqua_teen_hunger_force.yml", + "artist.yml", + "aviation.yml", + "back_to_the_future.yml", + "barcode.yml", + "bank.yml", + "basketball.yml", + "beer.yml", + "bojack_horseman.yml", + "book.yml", + "bossa_nova.yml", + "breaking_bad.yml", + "buffy.yml", + "business.yml", + "cannabis.yml", + "chuck_norris.yml", + "code.yml", + "coffee.yml", + "coin.yml", + "color.yml", + "commerce.yml", + "community.yml", + "company.yml", + "credit_card.yml", + "compass.yml", + "construction.yml", + "cosmere.yml", + "country.yml", + "crypto_coin.yml", + "currency.yml", + "dc_comics.yml", + "demographic.yml", + "dessert.yml", + "device.yml", + "disease.yml", + "dota.yml", + "dr_who.yml", + "dragon_ball.yml", + "dumb_and_dumber.yml", + "dune.yml", + "educator.yml", + "elder_scrolls.yml", + "electrical_components.yml", + "esport.yml", + "englandfootball.yml", + "fallout.yml", + "family_guy.yml", + "famous_last_words.yml", + "file.yml", + "finance.yml", + "food.yml", + "football.yml", + "fresh_prince_of_bel_air.yml", + "friends.yml", + "funny_name.yml", + "game_of_thrones.yml", + "gender.yml", + "ghostbusters.yml", + "grateful_dead.yml", + "greek_philosophers.yml", + "hacker.yml", + "half_life.yml", + "harry_potter.yml", + "heroes.yml", + "heroes_of_the_storm.yml", + "hey_arnold.yml", + "hipster.yml", + "hitchhikers_guide_to_the_galaxy.yml", + "hobbit.yml", + "house.yml", + "how_i_met_your_mother.yml", + "id_number.yml", + "industry_segments.yml", + "internet.yml", + "invoice.yml", + "job.yml", + "kpop.yml", + "lebowski.yml", + "lord_of_the_rings.yml", + "lorem.yml", + "lovecraft.yml", + "markdown.yml", + "marketing.yml", + "matz.yml", + "measurement.yml", + "medical.yml", + "michael_scott.yml", + "military.yml", + "most_interesting_man_in_the_world.yml", + "movie.yml", + "mountain.yml", + "music.yml", + "myst.yml", + "name.yml", + "nation.yml", + "nato_phonetic_alphabet.yml", + "new_girl.yml", + "one_piece.yml", + "overwatch.yml", + "parks_and_rec.yml", + "phish.yml", + "phone_number.yml", + "photography.yml", + "pokemon.yml", + "princess_bride.yml", + "programming_language.yml", + "relationship.yml", + "restaurant.yml", + "rick_and_morty.yml", + "robin.yml", + "rock_band.yml", + "rupaul.yml", + "science.yml", + "seinfeld.yml", + "shakespeare.yml", + "shipping.yml", + "silicon_valley.yml", + "simpsons.yml", + "singular_siegler.yml", + "sip.yml", + "slack_emoji.yml", + "sonic_the_hedgehog.yml", + "source.yml", + "south_park.yml", + "space.yml", + "starcraft.yml", + "star_trek.yml", + "star_wars.yml", + "stargate.yml", + "stock.yml", + "stranger_thing.yml", + "stripe.yml", + "subscription.yml", + "super_smash_bros.yml", + "superhero.yml", + "sword_art_online.yml", + "team.yml", + "the_expanse.yml", + "the_it_crowd.yml", + "the_thick_of_it.yml", + "twin_peaks.yml", + "umphreys_mcgee.yml", + "university.yml", + "v_for_vendetta.yml", + "vehicle.yml", + "venture_bros.yml", + "verbs.yml", + "weather.yml", + "witcher.yml", + "kaamelott.yml", + "world_cup.yml", + "world_of_warcraft.yml", + "yoda.yml", + "zelda.yml"); - public static List getFiles() { - List files = new ArrayList<>(); - for (String file : FILES) { - files.add(new EnFile(file)); - } - files.addAll(FILES_WITH_A_DIFFERENT_PATH); + // files where the search path can't be derived from the filename + private static List FILES_WITH_A_DIFFERENT_PATH = + Arrays.asList( + new EnFile("animal.yml", "creature"), + new EnFile("cat.yml", "creature"), + new EnFile("dog.yml", "creature"), + new EnFile("league_of_legends.yml", "games"), + new EnFile("overwatch.yml", "games"), + new EnFile("pokemon.yml", "games"), + new EnFile("witcher.yml", "games"), + new EnFile("zelda.yml", "games"), + new EnFile("elder_scrolls.yml", "games"), + new EnFile( + "phone_number.yml", "cell_phone")); // load phone number again with a differen path - return files; + public static List getFiles() { + List files = new ArrayList<>(); + for (String file : FILES) { + files.add(new EnFile(file)); } + files.addAll(FILES_WITH_A_DIFFERENT_PATH); + + return files; + } } diff --git a/src/test/java/org/thejavaguy/javafaker/AbstractFakerTest.java b/src/test/java/org/thejavaguy/javafaker/AbstractFakerTest.java index a4db117..d7e394d 100644 --- a/src/test/java/org/thejavaguy/javafaker/AbstractFakerTest.java +++ b/src/test/java/org/thejavaguy/javafaker/AbstractFakerTest.java @@ -4,7 +4,6 @@ import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.ExtendWith; @@ -15,25 +14,24 @@ @ExtendWith(RepeatRule.class) public class AbstractFakerTest { - @Spy - protected Faker faker; + @Spy protected Faker faker; - private AutoCloseable closeable; + private AutoCloseable closeable; - @BeforeEach - public void before() { - closeable = MockitoAnnotations.openMocks(this); + @BeforeEach + public void before() { + closeable = MockitoAnnotations.openMocks(this); - Logger rootLogger = LogManager.getLogManager().getLogger(""); - Handler[] handlers = rootLogger.getHandlers(); - rootLogger.setLevel(Level.INFO); - for (Handler h : handlers) { - h.setLevel(Level.INFO); - } + Logger rootLogger = LogManager.getLogManager().getLogger(""); + Handler[] handlers = rootLogger.getHandlers(); + rootLogger.setLevel(Level.INFO); + for (Handler h : handlers) { + h.setLevel(Level.INFO); } + } - @AfterEach - void closeMocks() throws Exception{ - closeable.close(); - } + @AfterEach + void closeMocks() throws Exception { + closeable.close(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/AddressTest.java b/src/test/java/org/thejavaguy/javafaker/AddressTest.java index fdf61e7..67caba1 100644 --- a/src/test/java/org/thejavaguy/javafaker/AddressTest.java +++ b/src/test/java/org/thejavaguy/javafaker/AddressTest.java @@ -5,119 +5,118 @@ import java.text.DecimalFormatSymbols; import java.util.Locale; import java.util.Random; - import org.junit.jupiter.api.Test; public class AddressTest extends AbstractFakerTest { - private static final char decimalSeparator = new DecimalFormatSymbols().getDecimalSeparator(); - - @Test - public void testStreetAddressStartsWithNumber() { - final String streetAddressNumber = faker.address().streetAddress(); - assertThat(streetAddressNumber).matches("[0-9]+ .+"); - } - - @Test - public void testStreetAddressIsANumber() { - final String streetAddressNumber = faker.address().streetAddressNumber(); - assertThat(streetAddressNumber).matches("[0-9]+"); - } - - @Test - public void testLatitude() { - String latStr; - Double lat; - for (int i = 0; i < 100; i++) { - latStr = faker.address().latitude().replace(decimalSeparator, '.'); - assertThat(latStr).matches("-?\\d+(\\.\\d+)?"); - lat = Double.valueOf(latStr); - assertThat(lat).as("Latitude is less then -90").isGreaterThanOrEqualTo(-90.0); - assertThat(lat).as("Latitude is greater than 90").isLessThanOrEqualTo(90.0); - } - } - - @Test - public void testLongitude() { - String longStr; - Double lon; - for (int i = 0; i < 100; i++) { - longStr = faker.address().longitude().replace(decimalSeparator, '.'); - assertThat(longStr).matches("-?\\d+(\\.\\d+)?"); - lon = Double.valueOf(longStr); - assertThat(lon).as("Longitude is less then -180").isGreaterThanOrEqualTo(-180.0); - assertThat(lon).as("Longitude is greater than 180").isLessThanOrEqualTo(180.0); - } - } - - @Test - public void testTimeZone() { - assertThat(faker.address().timeZone()).matches("[A-Za-z_]+/[A-Za-z_]+[/A-Za-z_]*"); - } - - @Test - public void testState() { - assertThat(faker.address().state()).matches("[A-Za-z ]+"); - } - - @Test - public void testCity() { - assertThat(faker.address().city()).matches("[A-Za-z'() ]+"); - } - - @Test - public void testCityName() { - assertThat(faker.address().cityName()).matches("[A-Za-z'() ]+"); - } - - @Test - public void testCountry() { - assertThat(faker.address().country()).matches("[A-Za-z\\- &.,'()\\d]+"); - } - - @Test - public void testCountryCode() { - assertThat(faker.address().countryCode()).matches("[A-Za-z ]+"); - } - - @Test - public void testStreetAddressIncludeSecondary() { - assertThat(faker.address().streetAddress(true)).isNotEmpty(); - } - - @Test - public void testCityWithLocaleFranceAndSeed() { - long seed = 1L; - Faker firstFaker = new Faker(Locale.FRANCE, new Random(seed)); - Faker secondFaker = new Faker(Locale.FRANCE, new Random(seed)); - assertThat(firstFaker.address().city()).isEqualTo(secondFaker.address().city()); - } - - @Test - public void testFullAddress() { - assertThat(faker.address().fullAddress()).isNotEmpty(); - } - - @Test - public void testZipCodeByState() { - faker = new Faker(new Locale("en-US")); - assertThat(faker.address().zipCodeByState(faker.address().stateAbbr())).matches("[0-9]{5}"); - } - - @Test - public void testHungarianZipCodeByState() { - faker = new Faker(new Locale("hu")); - assertThat(faker.address().zipCodeByState(faker.address().stateAbbr())).matches("[0-9]{4}"); - } - - @Test - public void testCountyByZipCode() { - faker = new Faker(new Locale("en-US")); - assertThat(faker.address().countyByZipCode("47732")).isNotEmpty(); - } - - @Test - public void testStreetPrefix() { - assertThat(faker.address().streetPrefix()).isNotBlank(); - } + private static final char decimalSeparator = new DecimalFormatSymbols().getDecimalSeparator(); + + @Test + public void testStreetAddressStartsWithNumber() { + final String streetAddressNumber = faker.address().streetAddress(); + assertThat(streetAddressNumber).matches("[0-9]+ .+"); + } + + @Test + public void testStreetAddressIsANumber() { + final String streetAddressNumber = faker.address().streetAddressNumber(); + assertThat(streetAddressNumber).matches("[0-9]+"); + } + + @Test + public void testLatitude() { + String latStr; + Double lat; + for (int i = 0; i < 100; i++) { + latStr = faker.address().latitude().replace(decimalSeparator, '.'); + assertThat(latStr).matches("-?\\d+(\\.\\d+)?"); + lat = Double.valueOf(latStr); + assertThat(lat).as("Latitude is less then -90").isGreaterThanOrEqualTo(-90.0); + assertThat(lat).as("Latitude is greater than 90").isLessThanOrEqualTo(90.0); + } + } + + @Test + public void testLongitude() { + String longStr; + Double lon; + for (int i = 0; i < 100; i++) { + longStr = faker.address().longitude().replace(decimalSeparator, '.'); + assertThat(longStr).matches("-?\\d+(\\.\\d+)?"); + lon = Double.valueOf(longStr); + assertThat(lon).as("Longitude is less then -180").isGreaterThanOrEqualTo(-180.0); + assertThat(lon).as("Longitude is greater than 180").isLessThanOrEqualTo(180.0); + } + } + + @Test + public void testTimeZone() { + assertThat(faker.address().timeZone()).matches("[A-Za-z_]+/[A-Za-z_]+[/A-Za-z_]*"); + } + + @Test + public void testState() { + assertThat(faker.address().state()).matches("[A-Za-z ]+"); + } + + @Test + public void testCity() { + assertThat(faker.address().city()).matches("[A-Za-z'() ]+"); + } + + @Test + public void testCityName() { + assertThat(faker.address().cityName()).matches("[A-Za-z'() ]+"); + } + + @Test + public void testCountry() { + assertThat(faker.address().country()).matches("[A-Za-z\\- &.,'()\\d]+"); + } + + @Test + public void testCountryCode() { + assertThat(faker.address().countryCode()).matches("[A-Za-z ]+"); + } + + @Test + public void testStreetAddressIncludeSecondary() { + assertThat(faker.address().streetAddress(true)).isNotEmpty(); + } + + @Test + public void testCityWithLocaleFranceAndSeed() { + long seed = 1L; + Faker firstFaker = new Faker(Locale.FRANCE, new Random(seed)); + Faker secondFaker = new Faker(Locale.FRANCE, new Random(seed)); + assertThat(firstFaker.address().city()).isEqualTo(secondFaker.address().city()); + } + + @Test + public void testFullAddress() { + assertThat(faker.address().fullAddress()).isNotEmpty(); + } + + @Test + public void testZipCodeByState() { + faker = new Faker(new Locale("en-US")); + assertThat(faker.address().zipCodeByState(faker.address().stateAbbr())).matches("[0-9]{5}"); + } + + @Test + public void testHungarianZipCodeByState() { + faker = new Faker(new Locale("hu")); + assertThat(faker.address().zipCodeByState(faker.address().stateAbbr())).matches("[0-9]{4}"); + } + + @Test + public void testCountyByZipCode() { + faker = new Faker(new Locale("en-US")); + assertThat(faker.address().countyByZipCode("47732")).isNotEmpty(); + } + + @Test + public void testStreetPrefix() { + assertThat(faker.address().streetPrefix()).isNotBlank(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/AncientTest.java b/src/test/java/org/thejavaguy/javafaker/AncientTest.java index b5a9761..78fa804 100644 --- a/src/test/java/org/thejavaguy/javafaker/AncientTest.java +++ b/src/test/java/org/thejavaguy/javafaker/AncientTest.java @@ -6,24 +6,23 @@ public class AncientTest extends AbstractFakerTest { - @Test - public void god() { - assertThat(faker.ancient().god()).matches("\\w+"); - } - - @Test - public void primordial() { - assertThat(faker.ancient().primordial()).matches("\\w+"); - } - - @Test - public void titan() { - assertThat(faker.ancient().titan()).matches("\\w+"); - } - - @Test - public void hero() { - assertThat(faker.ancient().hero()).matches("(?U)\\w+"); - } - + @Test + public void god() { + assertThat(faker.ancient().god()).matches("\\w+"); + } + + @Test + public void primordial() { + assertThat(faker.ancient().primordial()).matches("\\w+"); + } + + @Test + public void titan() { + assertThat(faker.ancient().titan()).matches("\\w+"); + } + + @Test + public void hero() { + assertThat(faker.ancient().hero()).matches("(?U)\\w+"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/AnimalTest.java b/src/test/java/org/thejavaguy/javafaker/AnimalTest.java index 621edef..6ba0e52 100644 --- a/src/test/java/org/thejavaguy/javafaker/AnimalTest.java +++ b/src/test/java/org/thejavaguy/javafaker/AnimalTest.java @@ -6,9 +6,8 @@ public class AnimalTest extends AbstractFakerTest { - @Test - public void name() { - assertThat(faker.animal().name()).matches("[A-Za-z ]+"); - } - + @Test + public void name() { + assertThat(faker.animal().name()).matches("[A-Za-z ]+"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/AppTest.java b/src/test/java/org/thejavaguy/javafaker/AppTest.java index b805209..a392f0c 100644 --- a/src/test/java/org/thejavaguy/javafaker/AppTest.java +++ b/src/test/java/org/thejavaguy/javafaker/AppTest.java @@ -6,18 +6,18 @@ public class AppTest extends AbstractFakerTest { - @Test - public void testName() { - assertThat(faker.app().name()).matches("([\\w-]+ ?)+"); - } + @Test + public void testName() { + assertThat(faker.app().name()).matches("([\\w-]+ ?)+"); + } - @Test - public void testVersion() { - assertThat(faker.app().version()).matches("\\d\\.(\\d){1,2}(\\.\\d)?"); - } + @Test + public void testVersion() { + assertThat(faker.app().version()).matches("\\d\\.(\\d){1,2}(\\.\\d)?"); + } - @Test - public void testAuthor() { - assertThat(faker.app().author()).matches("([\\w']+[-&,\\.]? ?){2,9}"); - } + @Test + public void testAuthor() { + assertThat(faker.app().author()).matches("([\\w']+[-&,\\.]? ?){2,9}"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/AquaTeenHungerForceTest.java b/src/test/java/org/thejavaguy/javafaker/AquaTeenHungerForceTest.java index 5b26701..e127d0e 100644 --- a/src/test/java/org/thejavaguy/javafaker/AquaTeenHungerForceTest.java +++ b/src/test/java/org/thejavaguy/javafaker/AquaTeenHungerForceTest.java @@ -6,9 +6,8 @@ public class AquaTeenHungerForceTest extends AbstractFakerTest { - @Test - public void character() { - assertThat(faker.aquaTeenHungerForce().character()).matches("[A-Za-z .]+"); - } - + @Test + public void character() { + assertThat(faker.aquaTeenHungerForce().character()).matches("[A-Za-z .]+"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/ArtistTest.java b/src/test/java/org/thejavaguy/javafaker/ArtistTest.java index 9a2d23f..6c348ff 100644 --- a/src/test/java/org/thejavaguy/javafaker/ArtistTest.java +++ b/src/test/java/org/thejavaguy/javafaker/ArtistTest.java @@ -6,8 +6,8 @@ public class ArtistTest extends AbstractFakerTest { - @Test - public void name() { - assertThat(faker.artist().name()).matches("(\\w+ ?){1,2}"); - } + @Test + public void name() { + assertThat(faker.artist().name()).matches("(\\w+ ?){1,2}"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/AvatarTest.java b/src/test/java/org/thejavaguy/javafaker/AvatarTest.java index 9148f94..d2a7156 100644 --- a/src/test/java/org/thejavaguy/javafaker/AvatarTest.java +++ b/src/test/java/org/thejavaguy/javafaker/AvatarTest.java @@ -7,10 +7,12 @@ public class AvatarTest extends AbstractFakerTest { - @TestTemplate - @Repeat(times=10) - public void testAvatar() { - String avatar = faker.avatar().image(); - assertThat(avatar).matches("^https:\\/\\/s3.amazonaws\\.com\\/uifaces\\/faces\\/twitter\\/[a-zA-Z0-9_]+\\/128\\.jpg$"); - } + @TestTemplate + @Repeat(times = 10) + public void testAvatar() { + String avatar = faker.avatar().image(); + assertThat(avatar) + .matches( + "^https:\\/\\/s3.amazonaws\\.com\\/uifaces\\/faces\\/twitter\\/[a-zA-Z0-9_]+\\/128\\.jpg$"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/AviationTest.java b/src/test/java/org/thejavaguy/javafaker/AviationTest.java index 2e6286d..4d08e4a 100644 --- a/src/test/java/org/thejavaguy/javafaker/AviationTest.java +++ b/src/test/java/org/thejavaguy/javafaker/AviationTest.java @@ -6,18 +6,18 @@ public class AviationTest extends AbstractFakerTest { - @Test - public void airport() { - assertThat(faker.aviation().airport()).matches("\\w{4}"); - } + @Test + public void airport() { + assertThat(faker.aviation().airport()).matches("\\w{4}"); + } - @Test - public void aircraft() { - assertThat(faker.aviation().aircraft()).isNotBlank(); - } + @Test + public void aircraft() { + assertThat(faker.aviation().aircraft()).isNotBlank(); + } - @Test - public void metar() { - assertThat(faker.aviation().METAR()).isNotBlank(); - } + @Test + public void metar() { + assertThat(faker.aviation().METAR()).isNotBlank(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/BackToTheFutureTest.java b/src/test/java/org/thejavaguy/javafaker/BackToTheFutureTest.java index 1d1009e..0ce2599 100644 --- a/src/test/java/org/thejavaguy/javafaker/BackToTheFutureTest.java +++ b/src/test/java/org/thejavaguy/javafaker/BackToTheFutureTest.java @@ -6,18 +6,20 @@ public class BackToTheFutureTest extends AbstractFakerTest { - @Test - public void character() { - assertThat(faker.backToTheFuture().character()).isNotBlank(); - } + @Test + public void character() { + assertThat(faker.backToTheFuture().character()).isNotBlank(); + } - @Test - public void date() { - assertThat(faker.backToTheFuture().date()).matches("([A-za-z]{3,8}) ([1-9]|[1-2]\\d|3[0-1]), (18[8-9]\\d|19[0-9]\\d|200\\d|201[0-5])"); - } + @Test + public void date() { + assertThat(faker.backToTheFuture().date()) + .matches( + "([A-za-z]{3,8}) ([1-9]|[1-2]\\d|3[0-1]), (18[8-9]\\d|19[0-9]\\d|200\\d|201[0-5])"); + } - @Test - public void quote() { - assertThat(faker.backToTheFuture().quote()).isNotBlank(); - } + @Test + public void quote() { + assertThat(faker.backToTheFuture().quote()).isNotBlank(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/BarcodeTest.java b/src/test/java/org/thejavaguy/javafaker/BarcodeTest.java index 72e0b0e..bc699c1 100644 --- a/src/test/java/org/thejavaguy/javafaker/BarcodeTest.java +++ b/src/test/java/org/thejavaguy/javafaker/BarcodeTest.java @@ -6,22 +6,22 @@ public class BarcodeTest extends AbstractFakerTest { - @Test - public void type() { - assertThat(faker.barcode().type()).matches( - "(Code(128|39|93))|(E|J)AN(-\\d{1,2})*|Codabar|UCC|UPC(-(A|E))*|IS(B|S)N|ITF|" + - "Ames\\sCode|NW-7|Monarch|Code\\s2\\sof\\s7|Rationalized|ANSI\\/AIM BC3-1995|USD-4|" + - "GS1 Databar|MSI Plessey"); - } + @Test + public void type() { + assertThat(faker.barcode().type()) + .matches( + "(Code(128|39|93))|(E|J)AN(-\\d{1,2})*|Codabar|UCC|UPC(-(A|E))*|IS(B|S)N|ITF|" + + "Ames\\sCode|NW-7|Monarch|Code\\s2\\sof\\s7|Rationalized|ANSI\\/AIM BC3-1995|USD-4|" + + "GS1 Databar|MSI Plessey"); + } - @Test - public void data(){ - assertThat(faker.barcode().data()).matches("\\d+"); - } - - @Test - public void typeAndData(){ - assertThat(faker.barcode().typeAndData()).matches("(\\w|\\W)+\\s\\d+$"); - } + @Test + public void data() { + assertThat(faker.barcode().data()).matches("\\d+"); + } + @Test + public void typeAndData() { + assertThat(faker.barcode().typeAndData()).matches("(\\w|\\W)+\\s\\d+$"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/BasketballTest.java b/src/test/java/org/thejavaguy/javafaker/BasketballTest.java index a54a552..8d4819d 100644 --- a/src/test/java/org/thejavaguy/javafaker/BasketballTest.java +++ b/src/test/java/org/thejavaguy/javafaker/BasketballTest.java @@ -7,66 +7,79 @@ public class BasketballTest extends AbstractFakerTest { - @Test - public void testPositions(){ - Faker faker=new Faker(); - assertThat(faker.basketball().positions()).matches("[\\p{L}'()\\., 0-9-’’]+"); } + @Test + public void testPositions() { + Faker faker = new Faker(); + assertThat(faker.basketball().positions()).matches("[\\p{L}'()\\., 0-9-’’]+"); + } - @Test - public void testTeams(){ - Faker faker=new Faker(); - assertThat(faker.basketball().teams()).matches("[\\p{L}'()\\., 0-9-’’]+"); } + @Test + public void testTeams() { + Faker faker = new Faker(); + assertThat(faker.basketball().teams()).matches("[\\p{L}'()\\., 0-9-’’]+"); + } - @Test - public void testCoaches(){ - Faker faker=new Faker(); - assertThat(faker.basketball().coaches()).matches("[\\p{L}'()\\., 0-9-’’]+"); } + @Test + public void testCoaches() { + Faker faker = new Faker(); + assertThat(faker.basketball().coaches()).matches("[\\p{L}'()\\., 0-9-’’]+"); + } - @Test - public void testPlayers(){ - Faker faker=new Faker(); - assertThat(faker.basketball().players()).matches("[\\p{L}'()\\., 0-9-’’]+"); } + @Test + public void testPlayers() { + Faker faker = new Faker(); + assertThat(faker.basketball().players()).matches("[\\p{L}'()\\., 0-9-’’]+"); + } - @Test - public void testPositionsWith10000Times(){ - Faker faker=new Faker(); - boolean isExist=false; - for(int i=0;i<10000;i++){ - String generateString=faker.basketball().positions(); - if(generateString.equals("Point Guard")){isExist=true;} - } - assertTrue(isExist); + @Test + public void testPositionsWith10000Times() { + Faker faker = new Faker(); + boolean isExist = false; + for (int i = 0; i < 10000; i++) { + String generateString = faker.basketball().positions(); + if (generateString.equals("Point Guard")) { + isExist = true; + } } + assertTrue(isExist); + } - @Test - public void testTeamsWith10000Times(){ - Faker faker=new Faker(); - boolean isExist=false; - for(int i=0;i<10000;i++){ - String generateString=faker.basketball().teams(); - if(generateString.equals("Atlanta Hawks")){isExist=true;} - } - assertTrue(isExist); + @Test + public void testTeamsWith10000Times() { + Faker faker = new Faker(); + boolean isExist = false; + for (int i = 0; i < 10000; i++) { + String generateString = faker.basketball().teams(); + if (generateString.equals("Atlanta Hawks")) { + isExist = true; + } } + assertTrue(isExist); + } - @Test - public void testCoachesWith10000Times(){ - Faker faker=new Faker(); - boolean isExist=false; - for(int i=0;i<10000;i++){ - String generateString=faker.basketball().coaches(); - if(generateString.equals("Kenny Atkinson")){isExist=true;} - } - assertTrue(isExist); + @Test + public void testCoachesWith10000Times() { + Faker faker = new Faker(); + boolean isExist = false; + for (int i = 0; i < 10000; i++) { + String generateString = faker.basketball().coaches(); + if (generateString.equals("Kenny Atkinson")) { + isExist = true; + } } + assertTrue(isExist); + } - @Test - public void testPlayersWith10000Times(){ - Faker faker=new Faker(); - boolean isExist=false; - for(int i=0;i<10000;i++){ - String generateString=faker.basketball().players(); - if(generateString.equals("Joel Embiid")){isExist=true;} - } - assertTrue(isExist); } + @Test + public void testPlayersWith10000Times() { + Faker faker = new Faker(); + boolean isExist = false; + for (int i = 0; i < 10000; i++) { + String generateString = faker.basketball().players(); + if (generateString.equals("Joel Embiid")) { + isExist = true; + } + } + assertTrue(isExist); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/BeerTest.java b/src/test/java/org/thejavaguy/javafaker/BeerTest.java index 54131a8..ac1742d 100644 --- a/src/test/java/org/thejavaguy/javafaker/BeerTest.java +++ b/src/test/java/org/thejavaguy/javafaker/BeerTest.java @@ -6,28 +6,28 @@ public class BeerTest extends AbstractFakerTest { - @Test - public void testName() { - assertThat(faker.beer().name()).matches("[\\p{L}'()\\., 0-9-’’]+"); - } - - @Test - public void testStyle() { - assertThat(faker.beer().style()).matches("[A-Za-z'() 0-9-]+"); - } - - @Test - public void testHop() { - assertThat(faker.beer().hop()).matches("[A-Za-z'’()\\. 0-9-]+"); - } - - @Test - public void testMalt() { - assertThat(faker.beer().malt()).matches("[A-Za-z'() 0-9-]+"); - } - - @Test - public void testYeast() { - assertThat(faker.beer().yeast()).matches("[\\p{L}'() 0-9-ö]+"); - } + @Test + public void testName() { + assertThat(faker.beer().name()).matches("[\\p{L}'()\\., 0-9-’’]+"); + } + + @Test + public void testStyle() { + assertThat(faker.beer().style()).matches("[A-Za-z'() 0-9-]+"); + } + + @Test + public void testHop() { + assertThat(faker.beer().hop()).matches("[A-Za-z'’()\\. 0-9-]+"); + } + + @Test + public void testMalt() { + assertThat(faker.beer().malt()).matches("[A-Za-z'() 0-9-]+"); + } + + @Test + public void testYeast() { + assertThat(faker.beer().yeast()).matches("[\\p{L}'() 0-9-ö]+"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/BojackHorsemanTest.java b/src/test/java/org/thejavaguy/javafaker/BojackHorsemanTest.java index 5bdf90b..beb49e5 100644 --- a/src/test/java/org/thejavaguy/javafaker/BojackHorsemanTest.java +++ b/src/test/java/org/thejavaguy/javafaker/BojackHorsemanTest.java @@ -8,54 +8,62 @@ public class BojackHorsemanTest extends AbstractFakerTest { - @Test - public void testCharacters1(){ - Faker faker=new Faker(); - assertThat(faker.bojackHorseman().characters()).matches("[\\p{L}'()\\., 0-9-’’]+"); } - - @Test - public void testQuotes1(){ - Faker faker=new Faker(); - assertFalse(faker.bojackHorseman().quotes().isEmpty()); } - - @Test - public void testTongueTwisters1(){ - Faker faker=new Faker(); - assertFalse(faker.bojackHorseman().tongueTwisters().isEmpty());} - - @Test - public void testCharactersWith10000Times(){ - Faker faker=new Faker(); - boolean isExist=false; - for(int i=0;i<10000;i++){ - String generateString=faker.bojackHorseman().characters(); - if(generateString.equals("Joseph Sugarman")){isExist=true;} - } - assertTrue(isExist); - } + @Test + public void testCharacters1() { + Faker faker = new Faker(); + assertThat(faker.bojackHorseman().characters()).matches("[\\p{L}'()\\., 0-9-’’]+"); + } + + @Test + public void testQuotes1() { + Faker faker = new Faker(); + assertFalse(faker.bojackHorseman().quotes().isEmpty()); + } - @Test - public void testQuotesWith10000Times(){ - Faker faker=new Faker(); - boolean isExist=false; - for(int i=0;i<10000;i++){ - String generateString=faker.bojackHorseman().quotes(); - if(generateString.equals("It gets easier. But you have to do it every day, that's the hard part. But it does get easier")) - {isExist=true;} - } - assertTrue(isExist); + @Test + public void testTongueTwisters1() { + Faker faker = new Faker(); + assertFalse(faker.bojackHorseman().tongueTwisters().isEmpty()); + } + + @Test + public void testCharactersWith10000Times() { + Faker faker = new Faker(); + boolean isExist = false; + for (int i = 0; i < 10000; i++) { + String generateString = faker.bojackHorseman().characters(); + if (generateString.equals("Joseph Sugarman")) { + isExist = true; + } } + assertTrue(isExist); + } - @Test - public void testTongueTwistersWith10000Times(){ - Faker faker=new Faker(); - boolean isExist=false; - for(int i=0;i<10000;i++){ - String generateString=faker.bojackHorseman().tongueTwisters(); - if(generateString.equals("Courtly roles like the formerly portly consort are Courtney Portnoy's forté")) - {isExist=true;} - } - assertTrue(isExist); + @Test + public void testQuotesWith10000Times() { + Faker faker = new Faker(); + boolean isExist = false; + for (int i = 0; i < 10000; i++) { + String generateString = faker.bojackHorseman().quotes(); + if (generateString.equals( + "It gets easier. But you have to do it every day, that's the hard part. But it does get easier")) { + isExist = true; + } } + assertTrue(isExist); + } + @Test + public void testTongueTwistersWith10000Times() { + Faker faker = new Faker(); + boolean isExist = false; + for (int i = 0; i < 10000; i++) { + String generateString = faker.bojackHorseman().tongueTwisters(); + if (generateString.equals( + "Courtly roles like the formerly portly consort are Courtney Portnoy's forté")) { + isExist = true; + } + } + assertTrue(isExist); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/BookTest.java b/src/test/java/org/thejavaguy/javafaker/BookTest.java index ee7be43..634b1a8 100644 --- a/src/test/java/org/thejavaguy/javafaker/BookTest.java +++ b/src/test/java/org/thejavaguy/javafaker/BookTest.java @@ -6,23 +6,23 @@ public class BookTest extends AbstractFakerTest { - @Test - public void testTitle() { - assertThat(faker.book().title()).matches("([\\p{L}'\\-\\?]+[!,]? ?){2,9}"); - } + @Test + public void testTitle() { + assertThat(faker.book().title()).matches("([\\p{L}'\\-\\?]+[!,]? ?){2,9}"); + } - @Test - public void testAuthor() { - assertThat(faker.book().author()).matches("([\\w']+\\.? ?){2,3}"); - } + @Test + public void testAuthor() { + assertThat(faker.book().author()).matches("([\\w']+\\.? ?){2,3}"); + } - @Test - public void testPublisher() { - assertThat(faker.book().publisher()).matches("([\\p{L}'&\\-]+[,.]? ?){1,5}"); - } + @Test + public void testPublisher() { + assertThat(faker.book().publisher()).matches("([\\p{L}'&\\-]+[,.]? ?){1,5}"); + } - @Test - public void testGenre() { - assertThat(faker.book().genre()).matches("([\\w/]+ ?){2,4}"); - } + @Test + public void testGenre() { + assertThat(faker.book().genre()).matches("([\\w/]+ ?){2,4}"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/BoolTest.java b/src/test/java/org/thejavaguy/javafaker/BoolTest.java index 32e7769..6b5123d 100644 --- a/src/test/java/org/thejavaguy/javafaker/BoolTest.java +++ b/src/test/java/org/thejavaguy/javafaker/BoolTest.java @@ -6,10 +6,10 @@ public class BoolTest extends AbstractFakerTest { - @Test - public void testBool() { - for (int i = 0; i < 100; i++) { - assertThat(faker.bool().bool()).isIn(true, false); - } + @Test + public void testBool() { + for (int i = 0; i < 100; i++) { + assertThat(faker.bool().bool()).isIn(true, false); } + } } diff --git a/src/test/java/org/thejavaguy/javafaker/BuffyTest.java b/src/test/java/org/thejavaguy/javafaker/BuffyTest.java index 4f07857..602b4b6 100644 --- a/src/test/java/org/thejavaguy/javafaker/BuffyTest.java +++ b/src/test/java/org/thejavaguy/javafaker/BuffyTest.java @@ -5,28 +5,28 @@ import org.junit.jupiter.api.Test; public class BuffyTest extends AbstractFakerTest { - @Test - public void testCharacters() { - assertThat(faker.buffy().characters()).isNotBlank(); - } + @Test + public void testCharacters() { + assertThat(faker.buffy().characters()).isNotBlank(); + } - @Test - public void testQuotes() { - assertThat(faker.buffy().quotes()).isNotBlank(); - } + @Test + public void testQuotes() { + assertThat(faker.buffy().quotes()).isNotBlank(); + } - @Test - public void testCelebrities() { - assertThat(faker.buffy().celebrities()).isNotBlank(); - } + @Test + public void testCelebrities() { + assertThat(faker.buffy().celebrities()).isNotBlank(); + } - @Test - public void testBigBads() { - assertThat(faker.buffy().bigBads()).isNotBlank(); - } + @Test + public void testBigBads() { + assertThat(faker.buffy().bigBads()).isNotBlank(); + } - @Test - public void testEpisodes() { - assertThat(faker.buffy().episodes()).isNotBlank(); - } + @Test + public void testEpisodes() { + assertThat(faker.buffy().episodes()).isNotBlank(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/BusinessTest.java b/src/test/java/org/thejavaguy/javafaker/BusinessTest.java index 124beb1..0f0c61e 100644 --- a/src/test/java/org/thejavaguy/javafaker/BusinessTest.java +++ b/src/test/java/org/thejavaguy/javafaker/BusinessTest.java @@ -5,19 +5,18 @@ import org.junit.jupiter.api.Test; public class BusinessTest extends AbstractFakerTest { - @Test - public void creditCardNumber() { - assertThat(faker.business().creditCardNumber()).isNotBlank(); - } + @Test + public void creditCardNumber() { + assertThat(faker.business().creditCardNumber()).isNotBlank(); + } - @Test - public void creditCardType() { - assertThat(faker.business().creditCardType()).isNotBlank(); - } - - @Test - public void creditCardExpiry() { - assertThat(faker.business().creditCardExpiry()).isNotBlank(); - } + @Test + public void creditCardType() { + assertThat(faker.business().creditCardType()).isNotBlank(); + } + @Test + public void creditCardExpiry() { + assertThat(faker.business().creditCardExpiry()).isNotBlank(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/CatTest.java b/src/test/java/org/thejavaguy/javafaker/CatTest.java index 884b4a3..057b298 100644 --- a/src/test/java/org/thejavaguy/javafaker/CatTest.java +++ b/src/test/java/org/thejavaguy/javafaker/CatTest.java @@ -6,18 +6,18 @@ public class CatTest extends AbstractFakerTest { - @Test - public void name() { - assertThat(faker.cat().name()).matches("[A-Za-z'() 0-9-]+"); - } + @Test + public void name() { + assertThat(faker.cat().name()).matches("[A-Za-z'() 0-9-]+"); + } - @Test - public void breed() { - assertThat(faker.cat().breed()).matches("[A-Za-z'() 0-9-,]+"); - } + @Test + public void breed() { + assertThat(faker.cat().breed()).matches("[A-Za-z'() 0-9-,]+"); + } - @Test - public void registry() { - assertThat(faker.cat().registry()).matches("[A-Za-zé'() 0-9-]+"); - } + @Test + public void registry() { + assertThat(faker.cat().registry()).matches("[A-Za-zé'() 0-9-]+"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/ChuckNorrisTest.java b/src/test/java/org/thejavaguy/javafaker/ChuckNorrisTest.java index 1637b2e..55e842e 100644 --- a/src/test/java/org/thejavaguy/javafaker/ChuckNorrisTest.java +++ b/src/test/java/org/thejavaguy/javafaker/ChuckNorrisTest.java @@ -6,8 +6,8 @@ public class ChuckNorrisTest extends AbstractFakerTest { - @Test - public void testFact() { - assertThat(faker.chuckNorris().fact()).isNotEmpty(); - } + @Test + public void testFact() { + assertThat(faker.chuckNorris().fact()).isNotEmpty(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/CodeTest.java b/src/test/java/org/thejavaguy/javafaker/CodeTest.java index b71efbc..c44acf0 100644 --- a/src/test/java/org/thejavaguy/javafaker/CodeTest.java +++ b/src/test/java/org/thejavaguy/javafaker/CodeTest.java @@ -3,7 +3,6 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.Locale; - import org.apache.commons.validator.routines.ISBNValidator; import org.apache.commons.validator.routines.checkdigit.EAN13CheckDigit; import org.apache.commons.validator.routines.checkdigit.LuhnCheckDigit; @@ -13,115 +12,115 @@ public class CodeTest extends AbstractFakerTest { - private static final ISBNValidator ISBN_VALIDATOR = ISBNValidator.getInstance(false); - - @TestTemplate - @Repeat(times = 1000) - public void isbn10DefaultIsNoSeparator() { - String isbn10 = faker.code().isbn10(); - - assertIsValidISBN10(isbn10); - assertThat(isbn10).doesNotContain("-"); - } - - @TestTemplate - @Repeat(times = 1000) - public void isbn13DefaultIsNoSeparator() { - String isbn13 = faker.code().isbn13(); - - assertIsValidISBN13(isbn13); - assertThat(isbn13).doesNotContain("-"); - } - - @TestTemplate - @Repeat(times = 1000) - public void testIsbn10() { - final String isbn10NoSep = faker.code().isbn10(false); - final String isbn10Sep = faker.code().isbn10(true); - - assertThat(isbn10NoSep).as(isbn10NoSep + " is not null").isNotNull(); - assertThat(isbn10NoSep.length()).as(isbn10NoSep + " has length of 10").isEqualTo(10); - assertIsValidISBN10(isbn10NoSep); - - assertThat(isbn10Sep).as(isbn10Sep + " is not null").isNotNull(); - assertThat(isbn10Sep.length()).as(isbn10Sep + " has length of 13").isEqualTo(13); - assertIsValidISBN10(isbn10Sep); - } - - @TestTemplate - @Repeat(times = 1000) - public void testIsbn13() { - final String isbn13NoSep = faker.code().isbn13(false); - final String isbn13Sep = faker.code().isbn13(true); - - assertThat(isbn13NoSep).as(isbn13NoSep + " is not null").isNotNull(); - assertThat(isbn13NoSep.length()).as(isbn13NoSep + " has length of 13").isEqualTo(13); - assertIsValidISBN13(isbn13NoSep); - - assertThat(isbn13Sep).as(isbn13Sep + " is not null").isNotNull(); - assertThat(isbn13Sep.length()).as(isbn13Sep + " has length of 17").isEqualTo(17); - assertIsValidISBN13(isbn13Sep); - } - - private void assertIsValidISBN10(String isbn10) { - assertThat(ISBN_VALIDATOR.isValidISBN10(isbn10)).as(isbn10 + " is valid").isEqualTo(true); - } - - private void assertIsValidISBN13(String isbn13) { - assertThat(ISBN_VALIDATOR.isValidISBN13(isbn13)).as(isbn13 + " is valid").isEqualTo(true); - } - - @TestTemplate - @Repeat(times = 100) - public void testOverrides() { - Faker faker = new Faker(new Locale("test")); - - final String isbn10Sep = faker.code().isbn10(true); - final String isbn13Sep = faker.code().isbn13(true); - - assertThat(isbn10Sep) - .as("Uses overridden expressions from test.yml") - .matches("9971-\\d-\\d{4}-(\\d|X)"); - - assertThat(isbn13Sep) - .as("Uses overridden expressions from test.yml") - .matches("(333|444)-9971-\\d-\\d{4}-\\d"); - } - - @Test - public void asin() { - assertThat(faker.code().asin()).matches("B000([A-Z]|\\d){6}"); - } - - @Test - public void imei() { - String imei = faker.code().imei(); - - assertThat(imei).matches("\\A[\\d\\.\\:\\-\\s]+\\z"); - assertThat(LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(imei)).isEqualTo(true); - } - - @Test - public void ean8() { - assertThat(faker.code().ean8()).matches("\\d{8}"); - } - - @Test - public void gtin8() { - assertThat(faker.code().gtin8()).matches("\\d{8}"); - } - - @Test - public void ean13() { - String ean13 = faker.code().ean13(); - assertThat(ean13).matches("\\d{13}"); - assertThat(EAN13CheckDigit.EAN13_CHECK_DIGIT.isValid(ean13)).isEqualTo(true); - } - - @Test - public void gtin13() { - String gtin13 = faker.code().gtin13(); - assertThat(gtin13).matches("\\d{13}"); - assertThat(EAN13CheckDigit.EAN13_CHECK_DIGIT.isValid(gtin13)).isEqualTo(true); - } + private static final ISBNValidator ISBN_VALIDATOR = ISBNValidator.getInstance(false); + + @TestTemplate + @Repeat(times = 1000) + public void isbn10DefaultIsNoSeparator() { + String isbn10 = faker.code().isbn10(); + + assertIsValidISBN10(isbn10); + assertThat(isbn10).doesNotContain("-"); + } + + @TestTemplate + @Repeat(times = 1000) + public void isbn13DefaultIsNoSeparator() { + String isbn13 = faker.code().isbn13(); + + assertIsValidISBN13(isbn13); + assertThat(isbn13).doesNotContain("-"); + } + + @TestTemplate + @Repeat(times = 1000) + public void testIsbn10() { + final String isbn10NoSep = faker.code().isbn10(false); + final String isbn10Sep = faker.code().isbn10(true); + + assertThat(isbn10NoSep).as(isbn10NoSep + " is not null").isNotNull(); + assertThat(isbn10NoSep.length()).as(isbn10NoSep + " has length of 10").isEqualTo(10); + assertIsValidISBN10(isbn10NoSep); + + assertThat(isbn10Sep).as(isbn10Sep + " is not null").isNotNull(); + assertThat(isbn10Sep.length()).as(isbn10Sep + " has length of 13").isEqualTo(13); + assertIsValidISBN10(isbn10Sep); + } + + @TestTemplate + @Repeat(times = 1000) + public void testIsbn13() { + final String isbn13NoSep = faker.code().isbn13(false); + final String isbn13Sep = faker.code().isbn13(true); + + assertThat(isbn13NoSep).as(isbn13NoSep + " is not null").isNotNull(); + assertThat(isbn13NoSep.length()).as(isbn13NoSep + " has length of 13").isEqualTo(13); + assertIsValidISBN13(isbn13NoSep); + + assertThat(isbn13Sep).as(isbn13Sep + " is not null").isNotNull(); + assertThat(isbn13Sep.length()).as(isbn13Sep + " has length of 17").isEqualTo(17); + assertIsValidISBN13(isbn13Sep); + } + + private void assertIsValidISBN10(String isbn10) { + assertThat(ISBN_VALIDATOR.isValidISBN10(isbn10)).as(isbn10 + " is valid").isEqualTo(true); + } + + private void assertIsValidISBN13(String isbn13) { + assertThat(ISBN_VALIDATOR.isValidISBN13(isbn13)).as(isbn13 + " is valid").isEqualTo(true); + } + + @TestTemplate + @Repeat(times = 100) + public void testOverrides() { + Faker faker = new Faker(new Locale("test")); + + final String isbn10Sep = faker.code().isbn10(true); + final String isbn13Sep = faker.code().isbn13(true); + + assertThat(isbn10Sep) + .as("Uses overridden expressions from test.yml") + .matches("9971-\\d-\\d{4}-(\\d|X)"); + + assertThat(isbn13Sep) + .as("Uses overridden expressions from test.yml") + .matches("(333|444)-9971-\\d-\\d{4}-\\d"); + } + + @Test + public void asin() { + assertThat(faker.code().asin()).matches("B000([A-Z]|\\d){6}"); + } + + @Test + public void imei() { + String imei = faker.code().imei(); + + assertThat(imei).matches("\\A[\\d\\.\\:\\-\\s]+\\z"); + assertThat(LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(imei)).isEqualTo(true); + } + + @Test + public void ean8() { + assertThat(faker.code().ean8()).matches("\\d{8}"); + } + + @Test + public void gtin8() { + assertThat(faker.code().gtin8()).matches("\\d{8}"); + } + + @Test + public void ean13() { + String ean13 = faker.code().ean13(); + assertThat(ean13).matches("\\d{13}"); + assertThat(EAN13CheckDigit.EAN13_CHECK_DIGIT.isValid(ean13)).isEqualTo(true); + } + + @Test + public void gtin13() { + String gtin13 = faker.code().gtin13(); + assertThat(gtin13).matches("\\d{13}"); + assertThat(EAN13CheckDigit.EAN13_CHECK_DIGIT.isValid(gtin13)).isEqualTo(true); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/CoinTest.java b/src/test/java/org/thejavaguy/javafaker/CoinTest.java index ecef914..c67bc7d 100644 --- a/src/test/java/org/thejavaguy/javafaker/CoinTest.java +++ b/src/test/java/org/thejavaguy/javafaker/CoinTest.java @@ -6,8 +6,8 @@ public class CoinTest extends AbstractFakerTest { - @Test - public void coinFlip() { - assertThat(faker.coin().flip()).matches("\\w+"); - } + @Test + public void coinFlip() { + assertThat(faker.coin().flip()).matches("\\w+"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/ColorTest.java b/src/test/java/org/thejavaguy/javafaker/ColorTest.java index 6d3422c..a900e39 100644 --- a/src/test/java/org/thejavaguy/javafaker/ColorTest.java +++ b/src/test/java/org/thejavaguy/javafaker/ColorTest.java @@ -6,18 +6,18 @@ public class ColorTest extends AbstractFakerTest { - @Test - public void testName() { - assertThat(faker.color().name()).matches("(\\w+ ?){1,2}"); - } + @Test + public void testName() { + assertThat(faker.color().name()).matches("(\\w+ ?){1,2}"); + } - @Test - public void testHex() { - assertThat(faker.color().hex()).matches("^#[0-9A-F]{6}$"); - } + @Test + public void testHex() { + assertThat(faker.color().hex()).matches("^#[0-9A-F]{6}$"); + } - @Test - public void testHexNoHashSign() { - assertThat(faker.color().hex(false)).matches("^[0-9A-F]{6}$"); - } + @Test + public void testHexNoHashSign() { + assertThat(faker.color().hex(false)).matches("^[0-9A-F]{6}$"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/CommerceTest.java b/src/test/java/org/thejavaguy/javafaker/CommerceTest.java index 983c947..1356733 100644 --- a/src/test/java/org/thejavaguy/javafaker/CommerceTest.java +++ b/src/test/java/org/thejavaguy/javafaker/CommerceTest.java @@ -3,54 +3,57 @@ import static org.assertj.core.api.Assertions.assertThat; import java.text.DecimalFormatSymbols; - import org.junit.jupiter.api.Test; public class CommerceTest extends AbstractFakerTest { - private static final char decimalSeparator = new DecimalFormatSymbols().getDecimalSeparator(); - - private static final String CAPITALIZED_WORD_REGEX = "[A-Z][a-z]+"; - - private static final String PROMOTION_CODE_REGEX = CAPITALIZED_WORD_REGEX + "(-" + CAPITALIZED_WORD_REGEX + ")*"; - - @Test - public void testColor() { - assertThat(faker.commerce().color()).matches("(\\w+ ?){1,2}"); - } - - @Test - public void testDepartment() { - assertThat(faker.commerce().department()).matches("(\\w+(, | & )?){1,3}"); - } - - @Test - public void testProductName() { - assertThat(faker.commerce().productName()).matches("(\\w+ ?){3,4}"); - } - - @Test - public void testMaterial() { - assertThat(faker.commerce().material()).matches("\\w+"); - } - - @Test - public void testPrice() { - assertThat(faker.commerce().price()).matches("\\d{1,3}\\" + decimalSeparator + "\\d{2}"); - } - - @Test - public void testPriceMinMax() { - assertThat(faker.commerce().price(100, 1000)).matches("\\d{3,4}\\" + decimalSeparator + "\\d{2}"); - } - - @Test - public void testPromotionCode() { - assertThat(faker.commerce().promotionCode()).matches(PROMOTION_CODE_REGEX + PROMOTION_CODE_REGEX + "\\d{6}"); - } - - @Test - public void testPromotionCodeDigits() { - assertThat(faker.commerce().promotionCode(3)).matches(PROMOTION_CODE_REGEX + PROMOTION_CODE_REGEX + "\\d{3}"); - } + private static final char decimalSeparator = new DecimalFormatSymbols().getDecimalSeparator(); + + private static final String CAPITALIZED_WORD_REGEX = "[A-Z][a-z]+"; + + private static final String PROMOTION_CODE_REGEX = + CAPITALIZED_WORD_REGEX + "(-" + CAPITALIZED_WORD_REGEX + ")*"; + + @Test + public void testColor() { + assertThat(faker.commerce().color()).matches("(\\w+ ?){1,2}"); + } + + @Test + public void testDepartment() { + assertThat(faker.commerce().department()).matches("(\\w+(, | & )?){1,3}"); + } + + @Test + public void testProductName() { + assertThat(faker.commerce().productName()).matches("(\\w+ ?){3,4}"); + } + + @Test + public void testMaterial() { + assertThat(faker.commerce().material()).matches("\\w+"); + } + + @Test + public void testPrice() { + assertThat(faker.commerce().price()).matches("\\d{1,3}\\" + decimalSeparator + "\\d{2}"); + } + + @Test + public void testPriceMinMax() { + assertThat(faker.commerce().price(100, 1000)) + .matches("\\d{3,4}\\" + decimalSeparator + "\\d{2}"); + } + + @Test + public void testPromotionCode() { + assertThat(faker.commerce().promotionCode()) + .matches(PROMOTION_CODE_REGEX + PROMOTION_CODE_REGEX + "\\d{6}"); + } + + @Test + public void testPromotionCodeDigits() { + assertThat(faker.commerce().promotionCode(3)) + .matches(PROMOTION_CODE_REGEX + PROMOTION_CODE_REGEX + "\\d{3}"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/CompanyTest.java b/src/test/java/org/thejavaguy/javafaker/CompanyTest.java index 4aeb9ba..5835e36 100644 --- a/src/test/java/org/thejavaguy/javafaker/CompanyTest.java +++ b/src/test/java/org/thejavaguy/javafaker/CompanyTest.java @@ -6,49 +6,51 @@ public class CompanyTest extends AbstractFakerTest { - @Test - public void testName() { - assertThat(faker.company().name()).matches("[A-Za-z\\-&', ]+"); - } - - @Test - public void testSuffix() { - assertThat(faker.company().suffix()).matches("[A-Za-z ]+"); - } - - @Test - public void testIndustry() { - assertThat(faker.company().industry()).matches("(\\w+([ ,&/-]{1,3})?){1,4}+"); - } - - @Test - public void testBuzzword() { - assertThat(faker.company().buzzword()).matches("(\\w+[ /-]?){1,3}"); - } - - @Test - public void testCatchPhrase() { - assertThat(faker.company().catchPhrase()).matches("(\\w+[ /-]?){1,9}"); - } - - @Test - public void testBs() { - assertThat(faker.company().bs()).matches("(\\w+[ /-]?){1,9}"); - } - - @Test - public void testLogo() { - assertThat(faker.company().logo()).matches("https://pigment.github.io/fake-logos/logos/medium/color/\\d+\\.png"); - } - - @Test - public void testProfession() { - assertThat(faker.company().profession()).matches("[a-z ]+"); - } - - @Test - public void testUrl() { - String regexp = "(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])"; - assertThat(faker.company().url()).matches(regexp); - } + @Test + public void testName() { + assertThat(faker.company().name()).matches("[A-Za-z\\-&', ]+"); + } + + @Test + public void testSuffix() { + assertThat(faker.company().suffix()).matches("[A-Za-z ]+"); + } + + @Test + public void testIndustry() { + assertThat(faker.company().industry()).matches("(\\w+([ ,&/-]{1,3})?){1,4}+"); + } + + @Test + public void testBuzzword() { + assertThat(faker.company().buzzword()).matches("(\\w+[ /-]?){1,3}"); + } + + @Test + public void testCatchPhrase() { + assertThat(faker.company().catchPhrase()).matches("(\\w+[ /-]?){1,9}"); + } + + @Test + public void testBs() { + assertThat(faker.company().bs()).matches("(\\w+[ /-]?){1,9}"); + } + + @Test + public void testLogo() { + assertThat(faker.company().logo()) + .matches("https://pigment.github.io/fake-logos/logos/medium/color/\\d+\\.png"); + } + + @Test + public void testProfession() { + assertThat(faker.company().profession()).matches("[a-z ]+"); + } + + @Test + public void testUrl() { + String regexp = + "(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])"; + assertThat(faker.company().url()).matches(regexp); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/CountryTest.java b/src/test/java/org/thejavaguy/javafaker/CountryTest.java index 26243eb..e4ed8df 100644 --- a/src/test/java/org/thejavaguy/javafaker/CountryTest.java +++ b/src/test/java/org/thejavaguy/javafaker/CountryTest.java @@ -8,41 +8,41 @@ public class CountryTest extends AbstractFakerTest { - @TestTemplate - @Repeat(times=10) - public void testFlag() { - String flag = faker.country().flag(); - assertThat(flag).matches("^http:\\/\\/flags.fmcdn\\.net\\/data\\/flags\\/w580\\/[a-zA-Z0-9_]+\\.png$"); - } - - - @Test - public void testCode2() { - assertThat(faker.country().countryCode2()).matches("([a-z]{2})"); - } - - @Test - public void testCode3() { - assertThat(faker.country().countryCode3()).matches("([a-z]{3})"); - } - - @Test - public void testCapital() { - assertThat(faker.country().capital()).matches("([\\w'-ç]+ ?)+"); - } - - @Test - public void testCurrency() { - assertThat(faker.country().currency()).matches("([A-Za-zÀ-ÿ'’()-]+ ?)+"); - } - - @Test - public void testCurrencyCode() { - assertThat(faker.country().currencyCode()).matches("([\\w-'’í]+ ?)+"); - } - - @Test - public void testName() { - assertThat(faker.country().name()).isNotBlank(); - } + @TestTemplate + @Repeat(times = 10) + public void testFlag() { + String flag = faker.country().flag(); + assertThat(flag) + .matches("^http:\\/\\/flags.fmcdn\\.net\\/data\\/flags\\/w580\\/[a-zA-Z0-9_]+\\.png$"); + } + + @Test + public void testCode2() { + assertThat(faker.country().countryCode2()).matches("([a-z]{2})"); + } + + @Test + public void testCode3() { + assertThat(faker.country().countryCode3()).matches("([a-z]{3})"); + } + + @Test + public void testCapital() { + assertThat(faker.country().capital()).matches("([\\w'-ç]+ ?)+"); + } + + @Test + public void testCurrency() { + assertThat(faker.country().currency()).matches("([A-Za-zÀ-ÿ'’()-]+ ?)+"); + } + + @Test + public void testCurrencyCode() { + assertThat(faker.country().currencyCode()).matches("([\\w-'’í]+ ?)+"); + } + + @Test + public void testName() { + assertThat(faker.country().name()).isNotBlank(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/CreditCardTest.java b/src/test/java/org/thejavaguy/javafaker/CreditCardTest.java index f930224..6302bf7 100644 --- a/src/test/java/org/thejavaguy/javafaker/CreditCardTest.java +++ b/src/test/java/org/thejavaguy/javafaker/CreditCardTest.java @@ -7,123 +7,124 @@ public class CreditCardTest extends AbstractFakerTest { - @Test - void number() { - String number = faker.creditCard().number(); - assertThat(number).isNotBlank(); - // Verify Luhn checksum - String stripped = number.replaceAll("[\\s-]", ""); - assertThat(LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(stripped)).isTrue(); - } - - @Test - void numberWithType() { - for (CreditCardType type : CreditCardType.values()) { - String number = faker.creditCard().number(type); - assertThat(number).isNotBlank(); - String stripped = number.replaceAll("[\\s-]", ""); - assertThat(LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(stripped)).isTrue(); - } - } - - @Test - void numberPlain() { - String number = faker.creditCard().numberPlain(); - assertThat(number).matches("\\d{13,19}"); - } - - @Test - void type() { - CreditCardType type = faker.creditCard().type(); - assertThat(type).isNotNull(); - assertThat(type).isIn((Object[]) CreditCardType.values()); - } - - @Test - void cvv() { - assertThat(faker.creditCard().cvv()).matches("\\d{3}"); - } - - @Test - void cvvForAmex() { - String cvv = faker.creditCard().cvv(CreditCardType.AMERICAN_EXPRESS); - assertThat(cvv).matches("\\d{4}"); - } - - @Test - void cvvForVisa() { - String cvv = faker.creditCard().cvv(CreditCardType.VISA); - assertThat(cvv).matches("\\d{3}"); - } - - @Test - void expirationDate() { - String expiry = faker.creditCard().expirationDate(); - assertThat(expiry).matches("\\d{2}/\\d{2}"); - } - - @Test - void expirationDateWithPattern() { - String expiry = faker.creditCard().expirationDate("MM/yyyy"); - assertThat(expiry).matches("\\d{2}/\\d{4}"); - } - - @Test - void expirationDateIsFuture() { - // Run multiple times to ensure consistency - for (int i = 0; i < 10; i++) { - String expiry = faker.creditCard().expirationDate("yyyy-MM"); - java.time.YearMonth expiryMonth = java.time.YearMonth.parse(expiry); - assertThat(expiryMonth).isAfter(java.time.YearMonth.now()); - } - } - - @Test - void expiredDate() { - String expiry = faker.creditCard().expiredDate(); - assertThat(expiry).matches("\\d{2}/\\d{2}"); - } - - @Test - void cardholderName() { - String name = faker.creditCard().cardholderName(); - assertThat(name).isNotBlank(); - assertThat(name).isUpperCase(); - assertThat(name).contains(" "); - } - - @Test - void bank() { - assertThat(faker.creditCard().bank()).isNotBlank(); - } - - @Test - void lastFourDigits() { - assertThat(faker.creditCard().lastFourDigits()).matches("\\d{4}"); - } - - @Test - void maskedNumber() { - String masked = faker.creditCard().maskedNumber(); - assertThat(masked).matches("\\*{4} \\*{4} \\*{4} \\d{4}"); - } - - @Test - void maskedNumberAmex() { - String masked = faker.creditCard().maskedNumber(CreditCardType.AMERICAN_EXPRESS); - assertThat(masked).matches("\\*{4} \\*{6} \\*\\d{4}"); - } - - @Test - void network() { - String network = faker.creditCard().network(); - assertThat(network).isNotBlank(); - } - - @Test - void networkForType() { - assertThat(faker.creditCard().network(CreditCardType.VISA)).isEqualTo("Visa"); - assertThat(faker.creditCard().network(CreditCardType.MASTERCARD)).isEqualTo("Mastercard"); - assertThat(faker.creditCard().network(CreditCardType.AMERICAN_EXPRESS)).isEqualTo("American Express"); - } + @Test + void number() { + String number = faker.creditCard().number(); + assertThat(number).isNotBlank(); + // Verify Luhn checksum + String stripped = number.replaceAll("[\\s-]", ""); + assertThat(LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(stripped)).isTrue(); + } + + @Test + void numberWithType() { + for (CreditCardType type : CreditCardType.values()) { + String number = faker.creditCard().number(type); + assertThat(number).isNotBlank(); + String stripped = number.replaceAll("[\\s-]", ""); + assertThat(LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(stripped)).isTrue(); + } + } + + @Test + void numberPlain() { + String number = faker.creditCard().numberPlain(); + assertThat(number).matches("\\d{13,19}"); + } + + @Test + void type() { + CreditCardType type = faker.creditCard().type(); + assertThat(type).isNotNull(); + assertThat(type).isIn((Object[]) CreditCardType.values()); + } + + @Test + void cvv() { + assertThat(faker.creditCard().cvv()).matches("\\d{3}"); + } + + @Test + void cvvForAmex() { + String cvv = faker.creditCard().cvv(CreditCardType.AMERICAN_EXPRESS); + assertThat(cvv).matches("\\d{4}"); + } + + @Test + void cvvForVisa() { + String cvv = faker.creditCard().cvv(CreditCardType.VISA); + assertThat(cvv).matches("\\d{3}"); + } + + @Test + void expirationDate() { + String expiry = faker.creditCard().expirationDate(); + assertThat(expiry).matches("\\d{2}/\\d{2}"); + } + + @Test + void expirationDateWithPattern() { + String expiry = faker.creditCard().expirationDate("MM/yyyy"); + assertThat(expiry).matches("\\d{2}/\\d{4}"); + } + + @Test + void expirationDateIsFuture() { + // Run multiple times to ensure consistency + for (int i = 0; i < 10; i++) { + String expiry = faker.creditCard().expirationDate("yyyy-MM"); + java.time.YearMonth expiryMonth = java.time.YearMonth.parse(expiry); + assertThat(expiryMonth).isAfter(java.time.YearMonth.now()); + } + } + + @Test + void expiredDate() { + String expiry = faker.creditCard().expiredDate(); + assertThat(expiry).matches("\\d{2}/\\d{2}"); + } + + @Test + void cardholderName() { + String name = faker.creditCard().cardholderName(); + assertThat(name).isNotBlank(); + assertThat(name).isUpperCase(); + assertThat(name).contains(" "); + } + + @Test + void bank() { + assertThat(faker.creditCard().bank()).isNotBlank(); + } + + @Test + void lastFourDigits() { + assertThat(faker.creditCard().lastFourDigits()).matches("\\d{4}"); + } + + @Test + void maskedNumber() { + String masked = faker.creditCard().maskedNumber(); + assertThat(masked).matches("\\*{4} \\*{4} \\*{4} \\d{4}"); + } + + @Test + void maskedNumberAmex() { + String masked = faker.creditCard().maskedNumber(CreditCardType.AMERICAN_EXPRESS); + assertThat(masked).matches("\\*{4} \\*{6} \\*\\d{4}"); + } + + @Test + void network() { + String network = faker.creditCard().network(); + assertThat(network).isNotBlank(); + } + + @Test + void networkForType() { + assertThat(faker.creditCard().network(CreditCardType.VISA)).isEqualTo("Visa"); + assertThat(faker.creditCard().network(CreditCardType.MASTERCARD)).isEqualTo("Mastercard"); + assertThat(faker.creditCard().network(CreditCardType.AMERICAN_EXPRESS)) + .isEqualTo("American Express"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/CryptoTest.java b/src/test/java/org/thejavaguy/javafaker/CryptoTest.java index 07131fd..7b233c1 100644 --- a/src/test/java/org/thejavaguy/javafaker/CryptoTest.java +++ b/src/test/java/org/thejavaguy/javafaker/CryptoTest.java @@ -4,26 +4,25 @@ import org.junit.jupiter.api.Test; - public class CryptoTest extends AbstractFakerTest { - @Test - public void testMd5() { - assertThat(faker.crypto().md5()).matches("[a-z\\d]+"); - } - - @Test - public void testSha1() { - assertThat(faker.crypto().sha1()).matches("[a-z\\d]+"); - } - - @Test - public void testSha256() { - assertThat(faker.crypto().sha256()).matches("[a-z\\d]+"); - } - - @Test - public void testSha512() { - assertThat(faker.crypto().sha512()).matches("[a-z\\d]+"); - } + @Test + public void testMd5() { + assertThat(faker.crypto().md5()).matches("[a-z\\d]+"); + } + + @Test + public void testSha1() { + assertThat(faker.crypto().sha1()).matches("[a-z\\d]+"); + } + + @Test + public void testSha256() { + assertThat(faker.crypto().sha256()).matches("[a-z\\d]+"); + } + + @Test + public void testSha512() { + assertThat(faker.crypto().sha512()).matches("[a-z\\d]+"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/CurrencyTest.java b/src/test/java/org/thejavaguy/javafaker/CurrencyTest.java index 538067e..865a510 100644 --- a/src/test/java/org/thejavaguy/javafaker/CurrencyTest.java +++ b/src/test/java/org/thejavaguy/javafaker/CurrencyTest.java @@ -6,15 +6,14 @@ public class CurrencyTest extends AbstractFakerTest { - @Test - public void testName() { - assertThat(faker.currency().name()).matches("[\\w\\'\\.\\-\\(\\) ]+"); - } - - @Test - public void testCode() { - final Currency currency = faker.currency(); - assertThat(currency.code()).matches("[A-Z]{3}"); - } + @Test + public void testName() { + assertThat(faker.currency().name()).matches("[\\w\\'\\.\\-\\(\\) ]+"); + } + @Test + public void testCode() { + final Currency currency = faker.currency(); + assertThat(currency.code()).matches("[A-Z]{3}"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/DateAndTimeTest.java b/src/test/java/org/thejavaguy/javafaker/DateAndTimeTest.java index d6cb4d5..0b28a92 100644 --- a/src/test/java/org/thejavaguy/javafaker/DateAndTimeTest.java +++ b/src/test/java/org/thejavaguy/javafaker/DateAndTimeTest.java @@ -8,7 +8,6 @@ import java.util.Date; import java.util.GregorianCalendar; import java.util.concurrent.TimeUnit; - import org.junit.jupiter.api.Test; /** @@ -16,110 +15,124 @@ */ public class DateAndTimeTest extends AbstractFakerTest { - @Test - public void testFutureDate() { - Date now = new Date(); + @Test + public void testFutureDate() { + Date now = new Date(); - for (int i = 0; i < 1000; i++) { - Date future = faker.date().future(1, TimeUnit.SECONDS, now); - assertThat(future.getTime()).as("past date").isGreaterThan(now.getTime()); - assertThat(future.getTime()).as("future date over range").isLessThan(now.getTime() + 1000); - } + for (int i = 0; i < 1000; i++) { + Date future = faker.date().future(1, TimeUnit.SECONDS, now); + assertThat(future.getTime()).as("past date").isGreaterThan(now.getTime()); + assertThat(future.getTime()).as("future date over range").isLessThan(now.getTime() + 1000); } - - @Test - public void testFutureDateWithMinimum(){ - for (int i = 0; i < 1000; i++) { - Date now = new Date(); - Date future = faker.date().future(5, 4, TimeUnit.SECONDS); - assertThat(future.getTime()).as("past date").isGreaterThan(now.getTime()); - assertThat(future.getTime()).as("future date over range").isLessThan(now.getTime() + 5001); - assertThat(future.getTime()).as("future date under minimum range").isGreaterThan(now.getTime() + 3999); - } + } + + @Test + public void testFutureDateWithMinimum() { + for (int i = 0; i < 1000; i++) { + Date now = new Date(); + Date future = faker.date().future(5, 4, TimeUnit.SECONDS); + assertThat(future.getTime()).as("past date").isGreaterThan(now.getTime()); + assertThat(future.getTime()).as("future date over range").isLessThan(now.getTime() + 5001); + assertThat(future.getTime()) + .as("future date under minimum range") + .isGreaterThan(now.getTime() + 3999); } - - @Test - public void testPastDateWithMinimum(){ - for (int i = 0; i < 1000; i++) { - Date now = new Date(); - Date past = faker.date().past(5, 4, TimeUnit.SECONDS); - assertThat(past.getTime()).as("future date").isLessThan(now.getTime()); - assertThat(past.getTime()).as("past date over range").isGreaterThan(now.getTime() - 5001); - assertThat(past.getTime()).as("past date under minimum range").isLessThan(now.getTime() - 3999); - } + } + + @Test + public void testPastDateWithMinimum() { + for (int i = 0; i < 1000; i++) { + Date now = new Date(); + Date past = faker.date().past(5, 4, TimeUnit.SECONDS); + assertThat(past.getTime()).as("future date").isLessThan(now.getTime()); + assertThat(past.getTime()).as("past date over range").isGreaterThan(now.getTime() - 5001); + assertThat(past.getTime()) + .as("past date under minimum range") + .isLessThan(now.getTime() - 3999); } + } - @Test - public void testPastDateWithReferenceDate() { - Date now = new Date(); + @Test + public void testPastDateWithReferenceDate() { + Date now = new Date(); - for (int i = 0; i < 1000; i++) { - Date past = faker.date().past(1, TimeUnit.SECONDS, now); - assertThat(past.getTime()).as("past date").isLessThan(now.getTime()); - assertThat(past.getTime()).as("past date over range").isGreaterThan(now.getTime() - 1000); - } + for (int i = 0; i < 1000; i++) { + Date past = faker.date().past(1, TimeUnit.SECONDS, now); + assertThat(past.getTime()).as("past date").isLessThan(now.getTime()); + assertThat(past.getTime()).as("past date over range").isGreaterThan(now.getTime() - 1000); } - - @Test - public void testPastDate() { - Date now = new Date(); - Date past = faker.date().past(100, TimeUnit.SECONDS); - assertThat(past.getTime()).as("past date is in the past").isLessThan(now.getTime()); - } - - @Test - public void testBetween() { - Date now = new Date(); - Date then = new Date(now.getTime() + 1000); - - for (int i = 0; i < 1000; i++) { - Date date = faker.date().between(now, then); - assertThat(date.getTime()).as("after upper bound").isLessThan(then.getTime()); - assertThat(date.getTime()).as("before lower bound").isGreaterThanOrEqualTo(now.getTime()); - } + } + + @Test + public void testPastDate() { + Date now = new Date(); + Date past = faker.date().past(100, TimeUnit.SECONDS); + assertThat(past.getTime()).as("past date is in the past").isLessThan(now.getTime()); + } + + @Test + public void testBetween() { + Date now = new Date(); + Date then = new Date(now.getTime() + 1000); + + for (int i = 0; i < 1000; i++) { + Date date = faker.date().between(now, then); + assertThat(date.getTime()).as("after upper bound").isLessThan(then.getTime()); + assertThat(date.getTime()).as("before lower bound").isGreaterThanOrEqualTo(now.getTime()); } - @Test - public void testBetweenThenLargerThanNow(){ - try{ - Date now = new Date(); - Date then = new Date(now.getTime() + 1000); - Date date =faker.date().between(then,now); - fail("Should be exception");}catch (IllegalArgumentException e){ - assertEquals("Invalid date range, the upper bound date is before the lower bound.", e.getMessage()); - } + } + + @Test + public void testBetweenThenLargerThanNow() { + try { + Date now = new Date(); + Date then = new Date(now.getTime() + 1000); + Date date = faker.date().between(then, now); + fail("Should be exception"); + } catch (IllegalArgumentException e) { + assertEquals( + "Invalid date range, the upper bound date is before the lower bound.", e.getMessage()); } - @Test - public void testBirthday() { - int currentYear = Calendar.getInstance().get(Calendar.YEAR); - int currentMonth = Calendar.getInstance().get(Calendar.MONTH); - int currentDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); - long from = new GregorianCalendar(currentYear - 65, currentMonth, currentDay).getTime().getTime(); - long to = new GregorianCalendar(currentYear - 18, currentMonth, currentDay).getTime().getTime(); - - for (int i = 0; i < 5000; i++) { - Date birthday = faker.date().birthday(); - assertThat(birthday.getTime()).as("birthday is after upper bound").isLessThan(to); - assertThat(birthday.getTime()).as("birthday is before lower bound").isGreaterThanOrEqualTo(from); - } + } + + @Test + public void testBirthday() { + int currentYear = Calendar.getInstance().get(Calendar.YEAR); + int currentMonth = Calendar.getInstance().get(Calendar.MONTH); + int currentDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); + long from = + new GregorianCalendar(currentYear - 65, currentMonth, currentDay).getTime().getTime(); + long to = new GregorianCalendar(currentYear - 18, currentMonth, currentDay).getTime().getTime(); + + for (int i = 0; i < 5000; i++) { + Date birthday = faker.date().birthday(); + assertThat(birthday.getTime()).as("birthday is after upper bound").isLessThan(to); + assertThat(birthday.getTime()) + .as("birthday is before lower bound") + .isGreaterThanOrEqualTo(from); } - - @Test - public void testBirthdayWithAges() { - int currentYear = Calendar.getInstance().get(Calendar.YEAR); - int currentMonth = Calendar.getInstance().get(Calendar.MONTH); - int currentDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); - - for (int i = 0; i < 5000; i++) { - int minAge = faker.number().numberBetween(1, 99); - int maxAge = faker.number().numberBetween(minAge, 100); - - long from = new GregorianCalendar(currentYear - maxAge, currentMonth, currentDay).getTime().getTime(); - long to = new GregorianCalendar(currentYear - minAge, currentMonth, currentDay).getTime().getTime(); - - Date birthday = faker.date().birthday(minAge, maxAge); - assertThat(birthday.getTime()).as("birthday is after upper bound").isLessThanOrEqualTo(to); - assertThat(birthday.getTime()).as("birthday is before lower bound").isGreaterThanOrEqualTo(from); - } + } + + @Test + public void testBirthdayWithAges() { + int currentYear = Calendar.getInstance().get(Calendar.YEAR); + int currentMonth = Calendar.getInstance().get(Calendar.MONTH); + int currentDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); + + for (int i = 0; i < 5000; i++) { + int minAge = faker.number().numberBetween(1, 99); + int maxAge = faker.number().numberBetween(minAge, 100); + + long from = + new GregorianCalendar(currentYear - maxAge, currentMonth, currentDay).getTime().getTime(); + long to = + new GregorianCalendar(currentYear - minAge, currentMonth, currentDay).getTime().getTime(); + + Date birthday = faker.date().birthday(minAge, maxAge); + assertThat(birthday.getTime()).as("birthday is after upper bound").isLessThanOrEqualTo(to); + assertThat(birthday.getTime()) + .as("birthday is before lower bound") + .isGreaterThanOrEqualTo(from); } - + } } diff --git a/src/test/java/org/thejavaguy/javafaker/DemographicTest.java b/src/test/java/org/thejavaguy/javafaker/DemographicTest.java index 2e6c229..abc18d7 100644 --- a/src/test/java/org/thejavaguy/javafaker/DemographicTest.java +++ b/src/test/java/org/thejavaguy/javafaker/DemographicTest.java @@ -6,28 +6,28 @@ public class DemographicTest extends AbstractFakerTest { - @Test - public void race() { - assertThat(faker.demographic().race()).matches("(\\w+ ?)+"); - } - - @Test - public void educationalAttainment() { - assertThat(faker.demographic().educationalAttainment()).matches("(?U)([\\w'-]+ ?)+"); - } - - @Test - public void demonym() { - assertThat(faker.demographic().demonym()).matches("(?U)([\\w'-]+ ?)+"); - } - - @Test - public void maritalStatus() { - assertThat(faker.demographic().maritalStatus()).matches("(\\w+ ?)+"); - } - - @Test - public void sex() { - assertThat(faker.demographic().sex()).matches("\\w+"); - } + @Test + public void race() { + assertThat(faker.demographic().race()).matches("(\\w+ ?)+"); + } + + @Test + public void educationalAttainment() { + assertThat(faker.demographic().educationalAttainment()).matches("(?U)([\\w'-]+ ?)+"); + } + + @Test + public void demonym() { + assertThat(faker.demographic().demonym()).matches("(?U)([\\w'-]+ ?)+"); + } + + @Test + public void maritalStatus() { + assertThat(faker.demographic().maritalStatus()).matches("(\\w+ ?)+"); + } + + @Test + public void sex() { + assertThat(faker.demographic().sex()).matches("\\w+"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/DiseaseTest.java b/src/test/java/org/thejavaguy/javafaker/DiseaseTest.java index 9a90705..6ba0ae0 100644 --- a/src/test/java/org/thejavaguy/javafaker/DiseaseTest.java +++ b/src/test/java/org/thejavaguy/javafaker/DiseaseTest.java @@ -8,102 +8,101 @@ import org.thejavaguy.javafaker.repeating.Repeat; public class DiseaseTest extends AbstractFakerTest { - @Test - public void testInternalDisease() { - Faker faker = new Faker(); - assertThat(faker.disease().internalDisease()).matches("[\\p{L}'()\\., 0-9-’’]+"); + @Test + public void testInternalDisease() { + Faker faker = new Faker(); + assertThat(faker.disease().internalDisease()).matches("[\\p{L}'()\\., 0-9-’’]+"); + } + + @Test + public void testNeurology() { + Faker faker = new Faker(); + assertThat(faker.disease().neurology()).matches("[\\p{L}'()\\., 0-9-’’]+"); + } + + @Test + public void testSurgery() { + Faker faker = new Faker(); + assertThat(faker.disease().surgery()).matches("[\\p{L}'()\\., 0-9-’’]+"); + } + + @Test + public void testPaediatrics() { + Faker faker = new Faker(); + assertThat(faker.disease().paediatrics()).matches("[\\p{L}'()\\., 0-9-’’]+"); + } + + @Test + public void testGynecologyAndObstetrics() { + Faker faker = new Faker(); + assertThat(faker.disease().gynecologyAndObstetrics()).matches("[\\p{L}'()\\., 0-9-’’]+"); + } + + @Test + public void testOphthalmologyAndOtorhinolaryngology() { + Faker faker = new Faker(); + assertThat(faker.disease().ophthalmologyAndOtorhinolaryngology()) + .matches("[\\p{L}'()\\., 0-9-’’]+"); + } + + @Test + public void testDermatolory() { + Faker faker = new Faker(); + assertThat(faker.disease().dermatolory()).matches("[\\p{L}'()\\., 0-9-’’]+"); + } + + @Test + public void testInternalDiseaseWith10000Times() { + Faker faker = new Faker(); + boolean isExist = false; + for (int i = 0; i < 10000; i++) { + String generateString = faker.disease().internalDisease(); + if (generateString.equals("anaphylaxis")) { + isExist = true; + } } - - @Test - public void testNeurology() { - Faker faker = new Faker(); - assertThat(faker.disease().neurology()).matches("[\\p{L}'()\\., 0-9-’’]+"); - } - - @Test - public void testSurgery() { - Faker faker = new Faker(); - assertThat(faker.disease().surgery()).matches("[\\p{L}'()\\., 0-9-’’]+"); - } - - @Test - public void testPaediatrics() { - Faker faker = new Faker(); - assertThat(faker.disease().paediatrics()).matches("[\\p{L}'()\\., 0-9-’’]+"); - } - - @Test - public void testGynecologyAndObstetrics() { - Faker faker = new Faker(); - assertThat(faker.disease().gynecologyAndObstetrics()).matches("[\\p{L}'()\\., 0-9-’’]+"); - } - - @Test - public void testOphthalmologyAndOtorhinolaryngology() { - Faker faker = new Faker(); - assertThat(faker.disease().ophthalmologyAndOtorhinolaryngology()).matches("[\\p{L}'()\\., 0-9-’’]+"); - } - - @Test - public void testDermatolory() { - Faker faker = new Faker(); - assertThat(faker.disease().dermatolory()).matches("[\\p{L}'()\\., 0-9-’’]+"); - } - - - @Test - public void testInternalDiseaseWith10000Times() { - Faker faker = new Faker(); - boolean isExist = false; - for (int i = 0; i < 10000; i++) { - String generateString = faker.disease().internalDisease(); - if (generateString.equals("anaphylaxis")) { - isExist = true; - } - } - assertTrue(isExist); - } - - @TestTemplate - @Repeat(times = 10000) - public void testNeurologyWith10000Times() { - Faker faker = new Faker(); - assertThat(faker.disease().neurology()).isNotBlank(); - } - - @TestTemplate - @Repeat(times = 10000) - public void testSurgeryWith10000Times() { - Faker faker = new Faker(); - assertThat(faker.disease().surgery()).isNotBlank(); - } - - @TestTemplate - @Repeat(times = 10000) - public void testPaediatricsWith10000Times() { - Faker faker = new Faker(); - assertThat(faker.disease().paediatrics()).isNotBlank(); - } - - @TestTemplate - @Repeat(times = 10000) - public void testGynecologyAndObstetricsWith10000Times() { - Faker faker = new Faker(); - assertThat(faker.disease().gynecologyAndObstetrics()).isNotBlank(); - } - - @TestTemplate - @Repeat(times = 10000) - public void testOphthalmologyAndOtorhinolaryngologyWith10000Times() { - Faker faker = new Faker(); - assertThat(faker.disease().ophthalmologyAndOtorhinolaryngology()).isNotBlank(); - } - - @TestTemplate - @Repeat(times = 10000) - public void testDermatoloryWith10000Times() { - Faker faker = new Faker(); - assertThat(faker.disease().dermatolory()).isNotBlank(); - } - + assertTrue(isExist); + } + + @TestTemplate + @Repeat(times = 10000) + public void testNeurologyWith10000Times() { + Faker faker = new Faker(); + assertThat(faker.disease().neurology()).isNotBlank(); + } + + @TestTemplate + @Repeat(times = 10000) + public void testSurgeryWith10000Times() { + Faker faker = new Faker(); + assertThat(faker.disease().surgery()).isNotBlank(); + } + + @TestTemplate + @Repeat(times = 10000) + public void testPaediatricsWith10000Times() { + Faker faker = new Faker(); + assertThat(faker.disease().paediatrics()).isNotBlank(); + } + + @TestTemplate + @Repeat(times = 10000) + public void testGynecologyAndObstetricsWith10000Times() { + Faker faker = new Faker(); + assertThat(faker.disease().gynecologyAndObstetrics()).isNotBlank(); + } + + @TestTemplate + @Repeat(times = 10000) + public void testOphthalmologyAndOtorhinolaryngologyWith10000Times() { + Faker faker = new Faker(); + assertThat(faker.disease().ophthalmologyAndOtorhinolaryngology()).isNotBlank(); + } + + @TestTemplate + @Repeat(times = 10000) + public void testDermatoloryWith10000Times() { + Faker faker = new Faker(); + assertThat(faker.disease().dermatolory()).isNotBlank(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/DogTest.java b/src/test/java/org/thejavaguy/javafaker/DogTest.java index ac3d4f3..91e3d97 100644 --- a/src/test/java/org/thejavaguy/javafaker/DogTest.java +++ b/src/test/java/org/thejavaguy/javafaker/DogTest.java @@ -6,43 +6,43 @@ public class DogTest extends AbstractFakerTest { - @Test - public void name() { - assertThat(faker.dog().name()).matches("[A-Za-z ]+"); - } - - @Test - public void breed() { - assertThat(faker.dog().breed()).matches("[A-Za-z ]+"); - } - - @Test - public void sound() { - assertThat(faker.dog().sound()).matches("[A-Za-z ]+"); - } - - @Test - public void memePhrase() { - assertThat(faker.dog().memePhrase()).matches("[A-Za-z0-9'\\/ ]+"); - } - - @Test - public void age() { - assertThat(faker.dog().age()).matches("[A-Za-z ]+"); - } - - @Test - public void gender() { - assertThat(faker.dog().gender()).matches("[A-Za-z ]+"); - } - - @Test - public void coatLength() { - assertThat(faker.dog().coatLength()).matches("[A-Za-z ]+"); - } - - @Test - public void size() { - assertThat(faker.dog().size()).matches("[A-Za-z ]+"); - } + @Test + public void name() { + assertThat(faker.dog().name()).matches("[A-Za-z ]+"); + } + + @Test + public void breed() { + assertThat(faker.dog().breed()).matches("[A-Za-z ]+"); + } + + @Test + public void sound() { + assertThat(faker.dog().sound()).matches("[A-Za-z ]+"); + } + + @Test + public void memePhrase() { + assertThat(faker.dog().memePhrase()).matches("[A-Za-z0-9'\\/ ]+"); + } + + @Test + public void age() { + assertThat(faker.dog().age()).matches("[A-Za-z ]+"); + } + + @Test + public void gender() { + assertThat(faker.dog().gender()).matches("[A-Za-z ]+"); + } + + @Test + public void coatLength() { + assertThat(faker.dog().coatLength()).matches("[A-Za-z ]+"); + } + + @Test + public void size() { + assertThat(faker.dog().size()).matches("[A-Za-z ]+"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/DragonBallTest.java b/src/test/java/org/thejavaguy/javafaker/DragonBallTest.java index 3028c69..257c758 100644 --- a/src/test/java/org/thejavaguy/javafaker/DragonBallTest.java +++ b/src/test/java/org/thejavaguy/javafaker/DragonBallTest.java @@ -6,8 +6,8 @@ public class DragonBallTest extends AbstractFakerTest { - @Test - public void character() { - assertThat(faker.dragonBall().character()).matches("^(\\w+\\.?\\s?-?)+$"); - } + @Test + public void character() { + assertThat(faker.dragonBall().character()).matches("^(\\w+\\.?\\s?-?)+$"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/DuneTest.java b/src/test/java/org/thejavaguy/javafaker/DuneTest.java index 7586643..d67dbcc 100644 --- a/src/test/java/org/thejavaguy/javafaker/DuneTest.java +++ b/src/test/java/org/thejavaguy/javafaker/DuneTest.java @@ -8,43 +8,40 @@ public class DuneTest extends AbstractFakerTest { - @Test - public void character() { - assertThat(faker.dune().character()).matches("[A-Za-z '\\-\"]+"); - } - - @Test - public void title() { - assertThat(faker.dune().title()).matches("[A-Za-z ]+"); - } - - @Test - public void planet() { - assertThat(faker.dune().planet()).matches("[A-Za-z ]+"); - } - - @Test - public void quote() { - assertThat(faker.dune().quote()).matches("\\P{Cc}+"); - } - - @TestTemplate - @Repeat(times = 10000) - public void randomQuote() { - assertThat( - faker.dune().quote(faker.options().option(Dune.Quote.class))).matches("\\P{Cc}+"); - } - - @Test - public void saying() { - assertThat(faker.dune().saying()).matches("\\P{Cc}+"); - } - - @TestTemplate - @Repeat(times = 10000) - public void randomSaying() { - assertThat( - faker.dune().saying(faker.options().option(Dune.Saying.class))).matches("\\P{Cc}+"); - } - + @Test + public void character() { + assertThat(faker.dune().character()).matches("[A-Za-z '\\-\"]+"); + } + + @Test + public void title() { + assertThat(faker.dune().title()).matches("[A-Za-z ]+"); + } + + @Test + public void planet() { + assertThat(faker.dune().planet()).matches("[A-Za-z ]+"); + } + + @Test + public void quote() { + assertThat(faker.dune().quote()).matches("\\P{Cc}+"); + } + + @TestTemplate + @Repeat(times = 10000) + public void randomQuote() { + assertThat(faker.dune().quote(faker.options().option(Dune.Quote.class))).matches("\\P{Cc}+"); + } + + @Test + public void saying() { + assertThat(faker.dune().saying()).matches("\\P{Cc}+"); + } + + @TestTemplate + @Repeat(times = 10000) + public void randomSaying() { + assertThat(faker.dune().saying(faker.options().option(Dune.Saying.class))).matches("\\P{Cc}+"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/EducatorTest.java b/src/test/java/org/thejavaguy/javafaker/EducatorTest.java index 5c6244e..7234ee2 100644 --- a/src/test/java/org/thejavaguy/javafaker/EducatorTest.java +++ b/src/test/java/org/thejavaguy/javafaker/EducatorTest.java @@ -6,23 +6,23 @@ public class EducatorTest extends AbstractFakerTest { - @Test - public void testUniversity() { - assertThat(faker.educator().university()).matches("(\\w+ ?){2,3}"); - } + @Test + public void testUniversity() { + assertThat(faker.educator().university()).matches("(\\w+ ?){2,3}"); + } - @Test - public void testCourse() { - assertThat(faker.educator().course()).matches("(\\(?\\w+\\)? ?){3,6}"); - } + @Test + public void testCourse() { + assertThat(faker.educator().course()).matches("(\\(?\\w+\\)? ?){3,6}"); + } - @Test - public void testSecondarySchool() { - assertThat(faker.educator().secondarySchool()).matches("(\\w+ ?){2,3}"); - } + @Test + public void testSecondarySchool() { + assertThat(faker.educator().secondarySchool()).matches("(\\w+ ?){2,3}"); + } - @Test - public void testCampus() { - assertThat(faker.educator().campus()).matches("(\\w+ ?){1,2}"); - } + @Test + public void testCampus() { + assertThat(faker.educator().campus()).matches("(\\w+ ?){1,2}"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/ElderScrollsTest.java b/src/test/java/org/thejavaguy/javafaker/ElderScrollsTest.java index 17d4f1a..9762ea4 100644 --- a/src/test/java/org/thejavaguy/javafaker/ElderScrollsTest.java +++ b/src/test/java/org/thejavaguy/javafaker/ElderScrollsTest.java @@ -4,45 +4,45 @@ import org.junit.jupiter.api.Test; -public class ElderScrollsTest extends AbstractFakerTest { - - @Test - public void testCity() { - assertThat(faker.elderScrolls().city()).isNotEmpty(); - } - - @Test - public void testCreature() { - assertThat(faker.elderScrolls().creature()).isNotEmpty(); - } - - @Test - public void testDragon() { - assertThat(faker.elderScrolls().dragon()).isNotEmpty(); - } - - @Test - public void testFirstName() { - assertThat(faker.elderScrolls().firstName()).isNotEmpty(); - } - - @Test - public void testLastName() { - assertThat(faker.elderScrolls().lastName()).isNotEmpty(); - } - - @Test - public void testRace() { - assertThat(faker.elderScrolls().race()).isNotEmpty(); - } - - @Test - public void testRegion() { - assertThat(faker.elderScrolls().region()).isNotEmpty(); - } - - @Test - public void testQuote() { - assertThat(faker.elderScrolls().quote()).isNotEmpty(); - } +public class ElderScrollsTest extends AbstractFakerTest { + + @Test + public void testCity() { + assertThat(faker.elderScrolls().city()).isNotEmpty(); + } + + @Test + public void testCreature() { + assertThat(faker.elderScrolls().creature()).isNotEmpty(); + } + + @Test + public void testDragon() { + assertThat(faker.elderScrolls().dragon()).isNotEmpty(); + } + + @Test + public void testFirstName() { + assertThat(faker.elderScrolls().firstName()).isNotEmpty(); + } + + @Test + public void testLastName() { + assertThat(faker.elderScrolls().lastName()).isNotEmpty(); + } + + @Test + public void testRace() { + assertThat(faker.elderScrolls().race()).isNotEmpty(); + } + + @Test + public void testRegion() { + assertThat(faker.elderScrolls().region()).isNotEmpty(); + } + + @Test + public void testQuote() { + assertThat(faker.elderScrolls().quote()).isNotEmpty(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/EnglandFootBallTest.java b/src/test/java/org/thejavaguy/javafaker/EnglandFootBallTest.java index 5e0eda1..d56cef6 100644 --- a/src/test/java/org/thejavaguy/javafaker/EnglandFootBallTest.java +++ b/src/test/java/org/thejavaguy/javafaker/EnglandFootBallTest.java @@ -4,16 +4,16 @@ import org.junit.jupiter.api.Test; -public class EnglandFootBallTest extends AbstractFakerTest{ - @Test - public void testLeague() { - String league = faker.englandfootball().league(); - assertThat(league).isNotEmpty(); - } +public class EnglandFootBallTest extends AbstractFakerTest { + @Test + public void testLeague() { + String league = faker.englandfootball().league(); + assertThat(league).isNotEmpty(); + } - @Test - public void testTeam() { - String team = faker.englandfootball().team(); - assertThat(team).isNotEmpty(); - } + @Test + public void testTeam() { + String team = faker.englandfootball().team(); + assertThat(team).isNotEmpty(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/EsportsTest.java b/src/test/java/org/thejavaguy/javafaker/EsportsTest.java index b2b5cc6..84c06af 100644 --- a/src/test/java/org/thejavaguy/javafaker/EsportsTest.java +++ b/src/test/java/org/thejavaguy/javafaker/EsportsTest.java @@ -6,28 +6,28 @@ public class EsportsTest extends AbstractFakerTest { - @Test - public void player() { - assertThat(faker.esports().player()).matches("(\\w|.)+"); - } - - @Test - public void team() { - assertThat(faker.esports().team()).matches("((\\w|.)+ ?)+"); - } - - @Test - public void event() { - assertThat(faker.esports().event()).matches("(\\w+ ?)+"); - } - - @Test - public void league() { - assertThat(faker.esports().league()).matches("\\w+"); - } - - @Test - public void game() { - assertThat(faker.esports().game()).matches("([\\w:.]+ ?)+"); - } + @Test + public void player() { + assertThat(faker.esports().player()).matches("(\\w|.)+"); + } + + @Test + public void team() { + assertThat(faker.esports().team()).matches("((\\w|.)+ ?)+"); + } + + @Test + public void event() { + assertThat(faker.esports().event()).matches("(\\w+ ?)+"); + } + + @Test + public void league() { + assertThat(faker.esports().league()).matches("\\w+"); + } + + @Test + public void game() { + assertThat(faker.esports().game()).matches("([\\w:.]+ ?)+"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/FakerTest.java b/src/test/java/org/thejavaguy/javafaker/FakerTest.java index fdeefa8..89c42a9 100644 --- a/src/test/java/org/thejavaguy/javafaker/FakerTest.java +++ b/src/test/java/org/thejavaguy/javafaker/FakerTest.java @@ -5,173 +5,173 @@ import java.util.Locale; import java.util.Random; - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestTemplate; import org.thejavaguy.javafaker.repeating.Repeat; public class FakerTest extends AbstractFakerTest { - @Test - public void bothifyShouldGenerateLettersAndNumbers() { - assertThat(faker.bothify("????##@gmail.com")).matches("\\w{4}\\d{2}@gmail.com"); - } - - @Test - public void letterifyShouldGenerateLetters() { - assertThat(faker.bothify("????")).matches("\\w{4}"); - } - - @Test - public void letterifyShouldGenerateUpperCaseLetters() { - assertThat(faker.bothify("????",true)).matches("[A-Z]{4}"); - } - - @Test - public void letterifyShouldLeaveNonSpecialCharactersAlone() { - assertThat(faker.bothify("ABC????DEF")).matches("ABC\\w{4}DEF"); - } - - @Test - public void numerifyShouldGenerateNumbers() { - assertThat(faker.numerify("####")).matches("\\d{4}"); - } - - @Test - public void numerifyShouldLeaveNonSpecialCharactersAlone() { - assertThat(faker.numerify("####123")).matches("\\d{4}123"); - } - - @Test - public void regexifyShouldGenerateNumbers() { - assertThat(faker.regexify("\\d")).matches("\\d"); - } - - @Test - public void regexifyShouldGenerateLetters() { - assertThat(faker.regexify("\\w")).matches("\\w"); - } - - @Test - public void regexifyShouldGenerateAlternations() { - assertThat(faker.regexify("(a|b)")).matches("(a|b)"); - } - - @Test - public void regexifyShouldGenerateBasicCharacterClasses() { - assertThat(faker.regexify("(aeiou)")).matches("(aeiou)"); - } - - @Test - public void regexifyShouldGenerateCharacterClassRanges() { - assertThat(faker.regexify("[a-z]")).matches("[a-z]"); - } - - @Test - public void regexifyShouldGenerateMultipleCharacterClassRanges() { - assertThat(faker.regexify("[a-z1-9]")).matches("[a-z1-9]"); - } - - @Test - public void regexifyShouldGenerateSingleCharacterQuantifiers() { - assertThat(faker.regexify("a*b+c?")).matches("a*b+c?"); - } - - @Test - public void regexifyShouldGenerateBracketsQuantifiers() { - assertThat(faker.regexify("a{2}")).matches("a{2}"); - } - - @Test - public void regexifyShouldGenerateMinMaxQuantifiers() { - assertThat(faker.regexify("a{2,3}")).matches("a{2,3}"); - } - - @Test - public void regexifyShouldGenerateBracketsQuantifiersOnBasicCharacterClasses() { - assertThat(faker.regexify("[aeiou]{2,3}")).matches("[aeiou]{2,3}"); - } - - @Test - public void regexifyShouldGenerateBracketsQuantifiersOnCharacterClassRanges() { - assertThat(faker.regexify("[a-z]{2,3}")).matches("[a-z]{2,3}"); - } - - @Test - public void regexifyShouldGenerateBracketsQuantifiersOnAlternations() { - assertThat(faker.regexify("(a|b){2,3}")).matches("(a|b){2,3}"); - } - - @Test - public void regexifyShouldGenerateEscapedCharacters() { - assertThat(faker.regexify("\\.\\*\\?\\+")).matches("\\.\\*\\?\\+"); - } - - @Test - public void badExpressionTooManyArgs() { - assertThrows(RuntimeException.class, () -> - faker.expression("#{regexify 'a','a'}")); - } - - @Test - public void badExpressionTooFewArgs() { - assertThrows(RuntimeException.class, () -> - faker.expression("#{regexify}")); - } - - @Test - public void badExpressionCouldntCoerce() { - assertThrows(RuntimeException.class, () -> - faker.expression("#{number.number_between 'x','10'}")); - } - - @Test - public void expression() { - assertThat(faker.expression("#{regexify '(a|b){2,3}'}")).matches("(a|b){2,3}"); - assertThat(faker.expression("#{regexify '\\.\\*\\?\\+'}")).matches("\\.\\*\\?\\+"); - assertThat(faker.expression("#{bothify '????','true'}")).matches("[A-Z]{4}"); - assertThat(faker.expression("#{bothify '????','false'}")).matches("[a-z]{4}"); - assertThat(faker.expression("#{letterify '????','true'}")).matches("[A-Z]{4}"); - assertThat(faker.expression("#{Name.first_name} #{Name.first_name} #{Name.last_name}")).matches("[a-zA-Z']+ [a-zA-Z']+ [a-zA-Z']+"); - assertThat(faker.expression("#{number.number_between '1','10'}")).matches("[1-9]"); - assertThat(faker.expression("#{color.name}")).matches("[a-z\\s]+"); - } - - @TestTemplate - @Repeat(times = 100) - public void numberBetweenRepeated() { - assertThat(faker.expression("#{number.number_between '1','10'}")).matches("[1-9]"); - } - - @Test - public void regexifyShouldGenerateSameValueForFakerWithSameSeed() { - long seed = 1L; - String regex = "\\d"; - - String firstResult = new Faker(new Random(seed)).regexify(regex); - String secondResult = new Faker(new Random(seed)).regexify(regex); - - assertThat(secondResult).isEqualTo(firstResult); - } - - @Test - public void resolveShouldReturnValueThatExists() { - assertThat(faker.resolve("address.city_prefix")).isNotEmpty(); - } - - @Test - public void resolveShouldThrowExceptionWhenPropertyDoesntExist() { - assertThrows(RuntimeException.class, () -> { - final String resolve = faker.resolve("address.nothing"); - assertThat(resolve).isNull(); + @Test + public void bothifyShouldGenerateLettersAndNumbers() { + assertThat(faker.bothify("????##@gmail.com")).matches("\\w{4}\\d{2}@gmail.com"); + } + + @Test + public void letterifyShouldGenerateLetters() { + assertThat(faker.bothify("????")).matches("\\w{4}"); + } + + @Test + public void letterifyShouldGenerateUpperCaseLetters() { + assertThat(faker.bothify("????", true)).matches("[A-Z]{4}"); + } + + @Test + public void letterifyShouldLeaveNonSpecialCharactersAlone() { + assertThat(faker.bothify("ABC????DEF")).matches("ABC\\w{4}DEF"); + } + + @Test + public void numerifyShouldGenerateNumbers() { + assertThat(faker.numerify("####")).matches("\\d{4}"); + } + + @Test + public void numerifyShouldLeaveNonSpecialCharactersAlone() { + assertThat(faker.numerify("####123")).matches("\\d{4}123"); + } + + @Test + public void regexifyShouldGenerateNumbers() { + assertThat(faker.regexify("\\d")).matches("\\d"); + } + + @Test + public void regexifyShouldGenerateLetters() { + assertThat(faker.regexify("\\w")).matches("\\w"); + } + + @Test + public void regexifyShouldGenerateAlternations() { + assertThat(faker.regexify("(a|b)")).matches("(a|b)"); + } + + @Test + public void regexifyShouldGenerateBasicCharacterClasses() { + assertThat(faker.regexify("(aeiou)")).matches("(aeiou)"); + } + + @Test + public void regexifyShouldGenerateCharacterClassRanges() { + assertThat(faker.regexify("[a-z]")).matches("[a-z]"); + } + + @Test + public void regexifyShouldGenerateMultipleCharacterClassRanges() { + assertThat(faker.regexify("[a-z1-9]")).matches("[a-z1-9]"); + } + + @Test + public void regexifyShouldGenerateSingleCharacterQuantifiers() { + assertThat(faker.regexify("a*b+c?")).matches("a*b+c?"); + } + + @Test + public void regexifyShouldGenerateBracketsQuantifiers() { + assertThat(faker.regexify("a{2}")).matches("a{2}"); + } + + @Test + public void regexifyShouldGenerateMinMaxQuantifiers() { + assertThat(faker.regexify("a{2,3}")).matches("a{2,3}"); + } + + @Test + public void regexifyShouldGenerateBracketsQuantifiersOnBasicCharacterClasses() { + assertThat(faker.regexify("[aeiou]{2,3}")).matches("[aeiou]{2,3}"); + } + + @Test + public void regexifyShouldGenerateBracketsQuantifiersOnCharacterClassRanges() { + assertThat(faker.regexify("[a-z]{2,3}")).matches("[a-z]{2,3}"); + } + + @Test + public void regexifyShouldGenerateBracketsQuantifiersOnAlternations() { + assertThat(faker.regexify("(a|b){2,3}")).matches("(a|b){2,3}"); + } + + @Test + public void regexifyShouldGenerateEscapedCharacters() { + assertThat(faker.regexify("\\.\\*\\?\\+")).matches("\\.\\*\\?\\+"); + } + + @Test + public void badExpressionTooManyArgs() { + assertThrows(RuntimeException.class, () -> faker.expression("#{regexify 'a','a'}")); + } + + @Test + public void badExpressionTooFewArgs() { + assertThrows(RuntimeException.class, () -> faker.expression("#{regexify}")); + } + + @Test + public void badExpressionCouldntCoerce() { + assertThrows( + RuntimeException.class, () -> faker.expression("#{number.number_between 'x','10'}")); + } + + @Test + public void expression() { + assertThat(faker.expression("#{regexify '(a|b){2,3}'}")).matches("(a|b){2,3}"); + assertThat(faker.expression("#{regexify '\\.\\*\\?\\+'}")).matches("\\.\\*\\?\\+"); + assertThat(faker.expression("#{bothify '????','true'}")).matches("[A-Z]{4}"); + assertThat(faker.expression("#{bothify '????','false'}")).matches("[a-z]{4}"); + assertThat(faker.expression("#{letterify '????','true'}")).matches("[A-Z]{4}"); + assertThat(faker.expression("#{Name.first_name} #{Name.first_name} #{Name.last_name}")) + .matches("[a-zA-Z']+ [a-zA-Z']+ [a-zA-Z']+"); + assertThat(faker.expression("#{number.number_between '1','10'}")).matches("[1-9]"); + assertThat(faker.expression("#{color.name}")).matches("[a-z\\s]+"); + } + + @TestTemplate + @Repeat(times = 100) + public void numberBetweenRepeated() { + assertThat(faker.expression("#{number.number_between '1','10'}")).matches("[1-9]"); + } + + @Test + public void regexifyShouldGenerateSameValueForFakerWithSameSeed() { + long seed = 1L; + String regex = "\\d"; + + String firstResult = new Faker(new Random(seed)).regexify(regex); + String secondResult = new Faker(new Random(seed)).regexify(regex); + + assertThat(secondResult).isEqualTo(firstResult); + } + + @Test + public void resolveShouldReturnValueThatExists() { + assertThat(faker.resolve("address.city_prefix")).isNotEmpty(); + } + + @Test + public void resolveShouldThrowExceptionWhenPropertyDoesntExist() { + assertThrows( + RuntimeException.class, + () -> { + final String resolve = faker.resolve("address.nothing"); + assertThat(resolve).isNull(); }); - } - - @Test - public void fakerInstanceCanBeAcquiredViaUtilityMethods() { - assertThat(Faker.instance()).isInstanceOf(Faker.class); - assertThat(Faker.instance(Locale.CANADA)).isInstanceOf(Faker.class); - assertThat(Faker.instance(new Random(1))).isInstanceOf(Faker.class); - assertThat(Faker.instance(Locale.CHINA, new Random(2))).isInstanceOf(Faker.class); - } + } + + @Test + public void fakerInstanceCanBeAcquiredViaUtilityMethods() { + assertThat(Faker.instance()).isInstanceOf(Faker.class); + assertThat(Faker.instance(Locale.CANADA)).isInstanceOf(Faker.class); + assertThat(Faker.instance(new Random(1))).isInstanceOf(Faker.class); + assertThat(Faker.instance(Locale.CHINA, new Random(2))).isInstanceOf(Faker.class); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/FileTest.java b/src/test/java/org/thejavaguy/javafaker/FileTest.java index 356142c..037aa12 100644 --- a/src/test/java/org/thejavaguy/javafaker/FileTest.java +++ b/src/test/java/org/thejavaguy/javafaker/FileTest.java @@ -8,45 +8,47 @@ public class FileTest extends AbstractFakerTest { - @TestTemplate - @Repeat(times=10) - public void testExtension() { - assertThat(faker.file().extension()).matches("(flac|mp3|wav|bmp|gif|jpeg|jpg|png|tiff|css|csv|html|js|json|txt|mp4|avi|mov|webm|doc|docx|xls|xlsx|ppt|pptx|odt|ods|odp|pages|numbers|key|pdf)"); - } - - @TestTemplate - @Repeat(times=10) - public void testMimeTypeFormat() { - assertThat(faker.file().mimeType()).matches(".+\\/.+"); - } - - @TestTemplate - @Repeat(times=10) - public void testFileName() { - assertThat(faker.file().fileName()).matches("([a-z\\-_]+)(\\\\|\\/)([a-z\\-_]+)\\.([a-z0-9]+)"); - } - - @Test - public void testFileNameSpecifyExtension() { - assertThat(faker.file().fileName(null, null, "txt", null)) - .matches("([a-z\\-_]+)(\\\\|\\/)([a-z\\-_]+)\\.txt"); - } - - @Test - public void testFileNameSpecifyDir() { - assertThat(faker.file().fileName("my_dir", null, null, null)) - .matches("my_dir(\\\\|\\/)([a-z\\-_]+)\\.([a-z0-9]+)"); - } - - @Test - public void testFileNameSpecifySeparator() { - assertThat(faker.file().fileName(null,null,null,"\\")) - .matches("([a-z\\-_]+)\\\\([a-z\\-_]+)\\.([a-z0-9]+)"); - } - - @Test - public void testFileNameSpecifyName() { - assertThat(faker.file().fileName(null,"da_name",null,null)) - .matches("([a-z\\-_]+)(\\\\|\\/)da_name\\.([a-z0-9]+)"); - } + @TestTemplate + @Repeat(times = 10) + public void testExtension() { + assertThat(faker.file().extension()) + .matches( + "(flac|mp3|wav|bmp|gif|jpeg|jpg|png|tiff|css|csv|html|js|json|txt|mp4|avi|mov|webm|doc|docx|xls|xlsx|ppt|pptx|odt|ods|odp|pages|numbers|key|pdf)"); + } + + @TestTemplate + @Repeat(times = 10) + public void testMimeTypeFormat() { + assertThat(faker.file().mimeType()).matches(".+\\/.+"); + } + + @TestTemplate + @Repeat(times = 10) + public void testFileName() { + assertThat(faker.file().fileName()).matches("([a-z\\-_]+)(\\\\|\\/)([a-z\\-_]+)\\.([a-z0-9]+)"); + } + + @Test + public void testFileNameSpecifyExtension() { + assertThat(faker.file().fileName(null, null, "txt", null)) + .matches("([a-z\\-_]+)(\\\\|\\/)([a-z\\-_]+)\\.txt"); + } + + @Test + public void testFileNameSpecifyDir() { + assertThat(faker.file().fileName("my_dir", null, null, null)) + .matches("my_dir(\\\\|\\/)([a-z\\-_]+)\\.([a-z0-9]+)"); + } + + @Test + public void testFileNameSpecifySeparator() { + assertThat(faker.file().fileName(null, null, null, "\\")) + .matches("([a-z\\-_]+)\\\\([a-z\\-_]+)\\.([a-z0-9]+)"); + } + + @Test + public void testFileNameSpecifyName() { + assertThat(faker.file().fileName(null, "da_name", null, null)) + .matches("([a-z\\-_]+)(\\\\|\\/)da_name\\.([a-z0-9]+)"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/FinanceTest.java b/src/test/java/org/thejavaguy/javafaker/FinanceTest.java index 03b0cd7..cf25a3e 100644 --- a/src/test/java/org/thejavaguy/javafaker/FinanceTest.java +++ b/src/test/java/org/thejavaguy/javafaker/FinanceTest.java @@ -7,39 +7,39 @@ public class FinanceTest extends AbstractFakerTest { - @Test - public void creditCard() { - for (int i = 0; i < 100; i++) { - final String creditCard = faker.finance().creditCard(); - assertCardLuhnDigit(creditCard); - } + @Test + public void creditCard() { + for (int i = 0; i < 100; i++) { + final String creditCard = faker.finance().creditCard(); + assertCardLuhnDigit(creditCard); } - - private void assertCardLuhnDigit(String creditCard) { - final String creditCardStripped = creditCard.replaceAll("-", ""); - assertThat(LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(creditCardStripped)).isEqualTo(true); - } - - @Test - public void bic() { - assertThat(faker.finance().bic()).matches("([A-Z]){4}([A-Z]){2}([0-9A-Z]){2}([0-9A-Z]{3})?"); - } - - @Test - public void iban() { - assertThat(faker.finance().iban()).matches("[A-Z]{2}\\p{Alnum}{13,30}"); - } - - @Test - public void ibanWithCountryCode() { - assertThat(faker.finance().iban("DE")).matches("DE\\d{20}"); - } - - @Test - public void creditCardWithType() { - for(CreditCardType type : CreditCardType.values()) { - final String creditCard = faker.finance().creditCard(type); - assertCardLuhnDigit(creditCard); - } + } + + private void assertCardLuhnDigit(String creditCard) { + final String creditCardStripped = creditCard.replaceAll("-", ""); + assertThat(LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(creditCardStripped)).isEqualTo(true); + } + + @Test + public void bic() { + assertThat(faker.finance().bic()).matches("([A-Z]){4}([A-Z]){2}([0-9A-Z]){2}([0-9A-Z]{3})?"); + } + + @Test + public void iban() { + assertThat(faker.finance().iban()).matches("[A-Z]{2}\\p{Alnum}{13,30}"); + } + + @Test + public void ibanWithCountryCode() { + assertThat(faker.finance().iban("DE")).matches("DE\\d{20}"); + } + + @Test + public void creditCardWithType() { + for (CreditCardType type : CreditCardType.values()) { + final String creditCard = faker.finance().creditCard(type); + assertCardLuhnDigit(creditCard); } + } } diff --git a/src/test/java/org/thejavaguy/javafaker/FoodTest.java b/src/test/java/org/thejavaguy/javafaker/FoodTest.java index 6adb439..0f6e720 100644 --- a/src/test/java/org/thejavaguy/javafaker/FoodTest.java +++ b/src/test/java/org/thejavaguy/javafaker/FoodTest.java @@ -6,38 +6,38 @@ public class FoodTest extends AbstractFakerTest { - @Test - public void ingredient() { - assertThat(faker.food().ingredient()).matches("[A-Za-z- ]+"); - } - - @Test - public void spice() { - assertThat(faker.food().spice()).matches("[A-Za-z1-9- ]+"); - } - - @Test - public void dish() { - assertThat(faker.food().dish()).matches("\\P{Cc}+"); - } - - @Test - public void fruit() { - assertThat(faker.food().fruit()).matches("[A-Za-z1-9- ]+"); - } - - @Test - public void vegetable() { - assertThat(faker.food().vegetable()).matches("[A-Za-z1-9- ]+"); - } - - @Test - public void sushi() { - assertThat(faker.food().sushi()).matches("[A-Za-z1-9- ]+"); - } - - @Test - public void measurement() { - assertThat(faker.food().measurement()).matches("[A-Za-z1-9/ ]+{2}"); - } + @Test + public void ingredient() { + assertThat(faker.food().ingredient()).matches("[A-Za-z- ]+"); + } + + @Test + public void spice() { + assertThat(faker.food().spice()).matches("[A-Za-z1-9- ]+"); + } + + @Test + public void dish() { + assertThat(faker.food().dish()).matches("\\P{Cc}+"); + } + + @Test + public void fruit() { + assertThat(faker.food().fruit()).matches("[A-Za-z1-9- ]+"); + } + + @Test + public void vegetable() { + assertThat(faker.food().vegetable()).matches("[A-Za-z1-9- ]+"); + } + + @Test + public void sushi() { + assertThat(faker.food().sushi()).matches("[A-Za-z1-9- ]+"); + } + + @Test + public void measurement() { + assertThat(faker.food().measurement()).matches("[A-Za-z1-9/ ]+{2}"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/FriendsTest.java b/src/test/java/org/thejavaguy/javafaker/FriendsTest.java index 4b01fed..6b50d37 100644 --- a/src/test/java/org/thejavaguy/javafaker/FriendsTest.java +++ b/src/test/java/org/thejavaguy/javafaker/FriendsTest.java @@ -6,18 +6,18 @@ public class FriendsTest extends AbstractFakerTest { - @Test - public void character() { - assertThat(faker.friends().character()).matches("[A-Za-z .,]+"); - } + @Test + public void character() { + assertThat(faker.friends().character()).matches("[A-Za-z .,]+"); + } - @Test - public void location() { - assertThat(faker.friends().location()).matches("[\\w.', ]+"); - } + @Test + public void location() { + assertThat(faker.friends().location()).matches("[\\w.', ]+"); + } - @Test - public void quote() { - assertThat(faker.friends().quote()).isNotEmpty(); - } + @Test + public void quote() { + assertThat(faker.friends().quote()).isNotEmpty(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/FunnyNameTest.java b/src/test/java/org/thejavaguy/javafaker/FunnyNameTest.java index 33ed5e4..e486243 100644 --- a/src/test/java/org/thejavaguy/javafaker/FunnyNameTest.java +++ b/src/test/java/org/thejavaguy/javafaker/FunnyNameTest.java @@ -6,8 +6,8 @@ public class FunnyNameTest extends AbstractFakerTest { - @Test - public void name() { - assertThat(faker.funnyName().name()).matches("^(\\w+\\.?\\s?'?-?)+$"); - } + @Test + public void name() { + assertThat(faker.funnyName().name()).matches("^(\\w+\\.?\\s?'?-?)+$"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/GameOfThronesTest.java b/src/test/java/org/thejavaguy/javafaker/GameOfThronesTest.java index f43c3ce..f812886 100644 --- a/src/test/java/org/thejavaguy/javafaker/GameOfThronesTest.java +++ b/src/test/java/org/thejavaguy/javafaker/GameOfThronesTest.java @@ -6,28 +6,28 @@ public class GameOfThronesTest extends AbstractFakerTest { - @Test - public void character() { - assertThat(faker.gameOfThrones().character()).matches("[A-Za-z'\\-\\(\\) ]+"); - } - - @Test - public void house() { - assertThat(faker.gameOfThrones().house()).matches("[A-Za-z' ]+"); - } - - @Test - public void city() { - assertThat(faker.gameOfThrones().city()).matches("[A-Za-z' ]+"); - } - - @Test - public void dragon() { - assertThat(faker.gameOfThrones().dragon()).matches("\\w+"); - } - - @Test - public void quote() { - assertThat(faker.gameOfThrones().quote()).isNotEmpty(); - } + @Test + public void character() { + assertThat(faker.gameOfThrones().character()).matches("[A-Za-z'\\-\\(\\) ]+"); + } + + @Test + public void house() { + assertThat(faker.gameOfThrones().house()).matches("[A-Za-z' ]+"); + } + + @Test + public void city() { + assertThat(faker.gameOfThrones().city()).matches("[A-Za-z' ]+"); + } + + @Test + public void dragon() { + assertThat(faker.gameOfThrones().dragon()).matches("\\w+"); + } + + @Test + public void quote() { + assertThat(faker.gameOfThrones().quote()).isNotEmpty(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/GenderTest.java b/src/test/java/org/thejavaguy/javafaker/GenderTest.java index 2e2b216..7105da4 100644 --- a/src/test/java/org/thejavaguy/javafaker/GenderTest.java +++ b/src/test/java/org/thejavaguy/javafaker/GenderTest.java @@ -6,19 +6,18 @@ public class GenderTest extends AbstractFakerTest { - @Test - public void types() { - assertThat(faker.gender().types()).matches("(\\w+ ?){1,2}"); - } + @Test + public void types() { + assertThat(faker.gender().types()).matches("(\\w+ ?){1,2}"); + } - @Test - public void binaryTypes() { - assertThat(faker.gender().binaryTypes()).matches("[A-Za-z ]+"); - } - - @Test - public void shortBinaryTypes() { - assertThat(faker.gender().shortBinaryTypes()).matches("f|m"); - } + @Test + public void binaryTypes() { + assertThat(faker.gender().binaryTypes()).matches("[A-Za-z ]+"); + } + @Test + public void shortBinaryTypes() { + assertThat(faker.gender().shortBinaryTypes()).matches("f|m"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/HackerTest.java b/src/test/java/org/thejavaguy/javafaker/HackerTest.java index 2fbc5ee..8993899 100644 --- a/src/test/java/org/thejavaguy/javafaker/HackerTest.java +++ b/src/test/java/org/thejavaguy/javafaker/HackerTest.java @@ -6,28 +6,28 @@ public class HackerTest extends AbstractFakerTest { - @Test - public void testAbbreviation() { - assertThat(faker.hacker().abbreviation()).matches("[A-Z]{2,4}"); - } - - @Test - public void testAdjective() { - assertThat(faker.hacker().adjective()).matches("(\\w+[- ]?){1,2}"); - } - - @Test - public void testNoun() { - assertThat(faker.hacker().noun()).matches("\\w+( \\w+)?"); - } - - @Test - public void testVerb() { - assertThat(faker.hacker().verb()).matches("\\w+( \\w+)?"); - } - - @Test - public void testIngverb() { - assertThat(faker.hacker().ingverb()).matches("\\w+ing( \\w+)?"); - } + @Test + public void testAbbreviation() { + assertThat(faker.hacker().abbreviation()).matches("[A-Z]{2,4}"); + } + + @Test + public void testAdjective() { + assertThat(faker.hacker().adjective()).matches("(\\w+[- ]?){1,2}"); + } + + @Test + public void testNoun() { + assertThat(faker.hacker().noun()).matches("\\w+( \\w+)?"); + } + + @Test + public void testVerb() { + assertThat(faker.hacker().verb()).matches("\\w+( \\w+)?"); + } + + @Test + public void testIngverb() { + assertThat(faker.hacker().ingverb()).matches("\\w+ing( \\w+)?"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/HarryPotterTest.java b/src/test/java/org/thejavaguy/javafaker/HarryPotterTest.java index 41333fc..00a1d0a 100644 --- a/src/test/java/org/thejavaguy/javafaker/HarryPotterTest.java +++ b/src/test/java/org/thejavaguy/javafaker/HarryPotterTest.java @@ -6,33 +6,33 @@ public class HarryPotterTest extends AbstractFakerTest { - @Test - public void character() { - assertThat(faker.harryPotter().character()).matches("[A-Za-z,\\-\\.\\(\\) ]+"); - } - - @Test - public void location() { - assertThat(faker.harryPotter().location()).matches("[A-Za-z0-9'\\. &,/]+"); - } - - @Test - public void quote() { - assertThat(faker.harryPotter().quote()).isNotEmpty(); - } - - @Test - public void book() { - assertThat(faker.harryPotter().book()).matches("Harry Potter and the ([A-Za-z'\\-]+ ?)+"); - } - - @Test - public void house() { - assertThat(faker.harryPotter().house()).matches("[A-Za-z ]+"); - } - - @Test - public void spell() { - assertThat(faker.harryPotter().spell()).matches("[A-Za-z ]+"); - } + @Test + public void character() { + assertThat(faker.harryPotter().character()).matches("[A-Za-z,\\-\\.\\(\\) ]+"); + } + + @Test + public void location() { + assertThat(faker.harryPotter().location()).matches("[A-Za-z0-9'\\. &,/]+"); + } + + @Test + public void quote() { + assertThat(faker.harryPotter().quote()).isNotEmpty(); + } + + @Test + public void book() { + assertThat(faker.harryPotter().book()).matches("Harry Potter and the ([A-Za-z'\\-]+ ?)+"); + } + + @Test + public void house() { + assertThat(faker.harryPotter().house()).matches("[A-Za-z ]+"); + } + + @Test + public void spell() { + assertThat(faker.harryPotter().spell()).matches("[A-Za-z ]+"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/HipsterTest.java b/src/test/java/org/thejavaguy/javafaker/HipsterTest.java index b964d74..0511f92 100644 --- a/src/test/java/org/thejavaguy/javafaker/HipsterTest.java +++ b/src/test/java/org/thejavaguy/javafaker/HipsterTest.java @@ -6,8 +6,8 @@ public class HipsterTest extends AbstractFakerTest { - @Test - public void word() { - assertThat(faker.hipster().word()).matches("^([\\w-+&']+ ?)+$"); - } + @Test + public void word() { + assertThat(faker.hipster().word()).matches("^([\\w-+&']+ ?)+$"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/HitchhikersGuideToTheGalaxyTest.java b/src/test/java/org/thejavaguy/javafaker/HitchhikersGuideToTheGalaxyTest.java index 5ffacf4..c4c66e2 100644 --- a/src/test/java/org/thejavaguy/javafaker/HitchhikersGuideToTheGalaxyTest.java +++ b/src/test/java/org/thejavaguy/javafaker/HitchhikersGuideToTheGalaxyTest.java @@ -7,33 +7,33 @@ public class HitchhikersGuideToTheGalaxyTest extends AbstractFakerTest { - @Test - public void character() { - assertThat(faker.hitchhikersGuideToTheGalaxy().character()).matches("^[\\w\\s.']+$"); - } - - @Test - public void location() { - assertThat(faker.hitchhikersGuideToTheGalaxy().location()).matches("^(\\w+\\S?\\.?\\s?'?-?)+$"); - } - - @Test - public void marvinQuote() { - assertFalse(faker.hitchhikersGuideToTheGalaxy().marvinQuote().isEmpty()); - } - - @Test - public void planet() { - assertThat(faker.hitchhikersGuideToTheGalaxy().planet()).matches("^(\\w+-?\\s?)+$"); - } - - @Test - public void quote() { - assertFalse(faker.hitchhikersGuideToTheGalaxy().quote().isEmpty()); - } - - @Test - public void specie() { - assertThat(faker.hitchhikersGuideToTheGalaxy().specie()).matches("^(\\w+'?\\s?)+$"); - } + @Test + public void character() { + assertThat(faker.hitchhikersGuideToTheGalaxy().character()).matches("^[\\w\\s.']+$"); + } + + @Test + public void location() { + assertThat(faker.hitchhikersGuideToTheGalaxy().location()).matches("^(\\w+\\S?\\.?\\s?'?-?)+$"); + } + + @Test + public void marvinQuote() { + assertFalse(faker.hitchhikersGuideToTheGalaxy().marvinQuote().isEmpty()); + } + + @Test + public void planet() { + assertThat(faker.hitchhikersGuideToTheGalaxy().planet()).matches("^(\\w+-?\\s?)+$"); + } + + @Test + public void quote() { + assertFalse(faker.hitchhikersGuideToTheGalaxy().quote().isEmpty()); + } + + @Test + public void specie() { + assertThat(faker.hitchhikersGuideToTheGalaxy().specie()).matches("^(\\w+'?\\s?)+$"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/HobbitTest.java b/src/test/java/org/thejavaguy/javafaker/HobbitTest.java index 834bb7e..aa0ffe8 100644 --- a/src/test/java/org/thejavaguy/javafaker/HobbitTest.java +++ b/src/test/java/org/thejavaguy/javafaker/HobbitTest.java @@ -7,23 +7,23 @@ public class HobbitTest extends AbstractFakerTest { - @Test - public void character() { - assertThat(faker.hobbit().character()).matches("^(\\(?\\w+\\.?\\s?\\)?)+$"); - } + @Test + public void character() { + assertThat(faker.hobbit().character()).matches("^(\\(?\\w+\\.?\\s?\\)?)+$"); + } - @Test - public void thorinsCompany() { - assertThat(faker.hobbit().thorinsCompany()).matches("^(\\w+\\s?)+$"); - } + @Test + public void thorinsCompany() { + assertThat(faker.hobbit().thorinsCompany()).matches("^(\\w+\\s?)+$"); + } - @Test - public void quote() { - assertFalse(faker.hobbit().quote().isEmpty()); - } + @Test + public void quote() { + assertFalse(faker.hobbit().quote().isEmpty()); + } - @Test - public void location() { - assertThat(faker.hobbit().location()).matches("^(\\w+'?-?\\s?)+$"); - } + @Test + public void location() { + assertThat(faker.hobbit().location()).matches("^(\\w+'?-?\\s?)+$"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/HowIMetYourMotherTest.java b/src/test/java/org/thejavaguy/javafaker/HowIMetYourMotherTest.java index e459ebf..3145ff4 100644 --- a/src/test/java/org/thejavaguy/javafaker/HowIMetYourMotherTest.java +++ b/src/test/java/org/thejavaguy/javafaker/HowIMetYourMotherTest.java @@ -7,23 +7,23 @@ public class HowIMetYourMotherTest extends AbstractFakerTest { - @Test - public void character() { - assertThat(faker.howIMetYourMother().character()).matches("^(\\w+\\.?\\s?)+$"); - } + @Test + public void character() { + assertThat(faker.howIMetYourMother().character()).matches("^(\\w+\\.?\\s?)+$"); + } - @Test - public void catchPhrase() { - assertFalse(faker.howIMetYourMother().catchPhrase().isEmpty()); - } + @Test + public void catchPhrase() { + assertFalse(faker.howIMetYourMother().catchPhrase().isEmpty()); + } - @Test - public void highFive() { - assertThat(faker.howIMetYourMother().highFive()).matches("^(\\w+-?\\s?)+$"); - } + @Test + public void highFive() { + assertThat(faker.howIMetYourMother().highFive()).matches("^(\\w+-?\\s?)+$"); + } - @Test - public void quote() { - assertFalse(faker.howIMetYourMother().quote().isEmpty()); - } + @Test + public void quote() { + assertFalse(faker.howIMetYourMother().quote().isEmpty()); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/IdNumberTest.java b/src/test/java/org/thejavaguy/javafaker/IdNumberTest.java index 4f67d8e..9122cfd 100644 --- a/src/test/java/org/thejavaguy/javafaker/IdNumberTest.java +++ b/src/test/java/org/thejavaguy/javafaker/IdNumberTest.java @@ -3,39 +3,38 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.Locale; - import org.junit.jupiter.api.Test; public class IdNumberTest extends AbstractFakerTest { - @Test - public void testValid() { - assertThat(faker.idNumber().valid()).matches("[0-8]\\d{2}-\\d{2}-\\d{4}"); - } - - @Test - public void testInvalid() { - assertThat(faker.idNumber().invalid()).matches("[0-9]\\d{2}-\\d{2}-\\d{4}"); - } - - @Test - public void testSsnValid() { - assertThat(faker.idNumber().valid()).matches("[0-8]\\d{2}-\\d{2}-\\d{4}"); - } - - @Test - public void testValidSwedishSsn() { - final Faker f = new Faker(new Locale("sv_SE")); - for (int i = 0; i < 100; i++) { - assertThat(f.idNumber().valid()).matches("\\d{6}[-+]\\d{4}"); - } + @Test + public void testValid() { + assertThat(faker.idNumber().valid()).matches("[0-8]\\d{2}-\\d{2}-\\d{4}"); + } + + @Test + public void testInvalid() { + assertThat(faker.idNumber().invalid()).matches("[0-9]\\d{2}-\\d{2}-\\d{4}"); + } + + @Test + public void testSsnValid() { + assertThat(faker.idNumber().valid()).matches("[0-8]\\d{2}-\\d{2}-\\d{4}"); + } + + @Test + public void testValidSwedishSsn() { + final Faker f = new Faker(new Locale("sv_SE")); + for (int i = 0; i < 100; i++) { + assertThat(f.idNumber().valid()).matches("\\d{6}[-+]\\d{4}"); } + } - @Test - public void testInvalidSwedishSsn() { - final Faker f = new Faker(new Locale("sv_SE")); - for (int i = 0; i < 100; i++) { - assertThat(f.idNumber().invalid()).matches("\\d{6}[-+]\\d{4}"); - } + @Test + public void testInvalidSwedishSsn() { + final Faker f = new Faker(new Locale("sv_SE")); + for (int i = 0; i < 100; i++) { + assertThat(f.idNumber().invalid()).matches("\\d{6}[-+]\\d{4}"); } + } } diff --git a/src/test/java/org/thejavaguy/javafaker/InternetTest.java b/src/test/java/org/thejavaguy/javafaker/InternetTest.java index 98f7a0a..c35768c 100644 --- a/src/test/java/org/thejavaguy/javafaker/InternetTest.java +++ b/src/test/java/org/thejavaguy/javafaker/InternetTest.java @@ -3,306 +3,310 @@ import static java.lang.Integer.parseInt; import static org.assertj.core.api.Assertions.assertThat; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; import java.util.List; import java.util.Locale; - import org.apache.commons.validator.routines.EmailValidator; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestTemplate; import org.thejavaguy.javafaker.repeating.Repeat; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; - public class InternetTest extends AbstractFakerTest { - @Test - public void testEmailAddress() { - String emailAddress = faker.internet().emailAddress(); - assertThat(EmailValidator.getInstance().isValid(emailAddress)).isEqualTo(true); - } - - @Test - public void testEmailAddressWithLocalPartParameter() { - String emailAddress = faker.internet().emailAddress("john"); - assertThat(emailAddress).startsWith("john@"); - assertThat(EmailValidator.getInstance().isValid(emailAddress)).isEqualTo(true); - } - - @Test - public void testSafeEmailAddress() { - List emails = Lists.newArrayList(); - for (int i=0;i<100;i++) { - String emailAddress = faker.internet().safeEmailAddress(); - assertThat(EmailValidator.getInstance().isValid(emailAddress)).isEqualTo(true); - emails.add(emailAddress); - } - final String safeDomain = faker.resolve("internet.safe_email"); - - assertThat(emails) - .as("Should find at least one email from " + safeDomain) - .anyMatch(email -> email.endsWith("@" + safeDomain)); - } - - @Test - public void testSafeEmailAddressWithLocalPartParameter() { - List emails = Lists.newArrayList(); - for (int i=0;i<100;i++) { - String emailAddress = faker.internet().safeEmailAddress("john"); - assertThat(emailAddress).startsWith("john@"); - assertThat(EmailValidator.getInstance().isValid(emailAddress)).isEqualTo(true); - emails.add(emailAddress); - } - final String safeDomain = faker.resolve("internet.safe_email"); - - assertThat(emails) - .as("Should find at least one email from " + safeDomain) - .anyMatch(email -> email.endsWith("@" + safeDomain)); - } - - @Test - public void testEmailAddressDoesNotIncludeAccentsInTheLocalPart() { - String emailAddress = faker.internet().emailAddress("áéíóú"); - assertThat(emailAddress).startsWith("aeiou@"); - } - - @Test - public void testSafeEmailAddressDoesNotIncludeAccentsInTheLocalPart() { - String emailAddress = faker.internet().safeEmailAddress("áéíóú"); - assertThat(emailAddress).startsWith("aeiou@"); - } - - @Test - public void testUrl() { - assertThat(faker.internet().url()).matches("www\\.(\\w|-)+\\.\\w+"); - } - - @Test - public void testAvatar() { - assertThat(faker.internet().avatar()).matches("http.*/[^/]+/128.jpg$"); - } - - @Test - public void testImage() { - String imageUrl = faker.internet().image(); - assertThat(imageUrl).matches("^http:\\/\\/lorempixel\\.com(/g)?/\\d{1,4}/\\d{1,4}/\\w+/$"); - } - - @Test - public void testDomainName() { - assertThat(faker.internet().domainName()).matches("[a-z]+\\.\\w{2,4}"); - } - - @Test - public void testDomainWord() { - assertThat(faker.internet().domainWord()).matches("[a-z]+"); - } - - @Test - public void testDomainSuffix() { - assertThat(faker.internet().domainSuffix()).matches("\\w{2,4}"); - } - - @Test - public void testImageWithExplicitParams() { - String imageUrl = faker.internet().image(800, 600, false, "bugs"); - assertThat(imageUrl).matches("^http:\\/\\/lorempixel\\.com/800/600/\\w+/bugs$"); - } - - @Test - public void testPassword() { - assertThat(faker.internet().password()).matches("[a-z\\d]{8,16}"); - } - - @Test - public void testPasswordIncludeDigit() { - assertThat(faker.internet().password()).matches("[a-z\\d]{8,16}"); - assertThat(faker.internet().password(false)).matches("[a-z]{8,16}"); - } - - @Test - public void testPasswordMinLengthMaxLength() { - assertThat(faker.internet().password(10, 25)).matches("[a-z\\d]{10,25}"); - } - - @Test - public void testPasswordMinLengthMaxLengthIncludeUpperCase() { - assertThat(faker.internet().password(1, 2, false)).matches("[a-z\\d]{1,2}"); - assertThat(faker.internet().password(10, 25, true)).matches("[a-zA-Z\\d]{10,25}"); - } - - @Test - public void testPasswordMinLengthMaxLengthIncludeUpperCaseIncludeSpecial() { - assertThat(faker.internet().password(10, 25, false, false)).matches("[a-z\\d]{10,25}"); - assertThat(faker.internet().password(10, 25, false, true)).matches("[a-z\\d!@#$%^&*]{10,25}"); - assertThat(faker.internet().password(10, 25, true, true)).matches("[a-zA-Z\\d!@#$%^&*]{10,25}"); - } - - @Test - public void testPasswordMinLengthMaxLengthIncludeUpperCaseIncludeSpecialIncludeDigit() { - assertThat(faker.internet().password(10, 25, false, false, false)).matches("[a-z]{10,25}"); - assertThat(faker.internet().password(10, 25, false, true, true)).matches("[a-z\\d!@#$%^&*]{10,25}"); - assertThat(faker.internet().password(10, 25, true, true, false)).matches("[a-zA-Z!@#$%^&*]{10,25}"); - assertThat(faker.internet().password(10, 25, true, true, true)).matches("[a-zA-Z\\d!@#$%^&*]{10,25}"); - } - - @Test - public void testMacAddress() { - assertThat(faker.internet().macAddress().chars().filter(c -> c == ':').count()).isEqualTo(5); - assertThat(faker.internet().macAddress("").chars().filter(c -> c == ':').count()).isEqualTo(5); - - assertThat(faker.internet().macAddress("fa:fa:fa")).startsWith("fa:fa:fa"); - assertThat(faker.internet().macAddress("fa:fa:fa").chars().filter(c -> c == ':').count()).isEqualTo(5); - - assertThat(faker.internet().macAddress("01:02")).startsWith("01:02"); - assertThat(faker.internet().macAddress("01:02").chars().filter(c -> c == ':').count()).isEqualTo(5); - - // loop through 1000 times just to 'run it through the wringer' - for (int i=0; i<1000;i++) { - assertThat(faker.internet().macAddress()).matches("[0-9a-fA-F]{2}(\\:([0-9a-fA-F]{1,4})){5}"); - } - } - - @Test - public void testIpV4Address() { - assertThat(faker.internet().ipV4Address().chars().filter(c -> c == '.').count()).isEqualTo(3); - for (int i = 0; i < 100; i++) { - final String[] octets = faker.internet().ipV4Address().split("\\."); - assertThat(parseInt(octets[0])) - .as("first octet is 1-255") - .isGreaterThanOrEqualTo(0) - .isLessThanOrEqualTo(255); - assertThat(parseInt(octets[1])) - .as("second octet is 0-255") - .isGreaterThanOrEqualTo(0) - .isLessThanOrEqualTo(255); - assertThat(parseInt(octets[2])) - .as("third octet is 0-255") - .isGreaterThanOrEqualTo(0) - .isLessThanOrEqualTo(255); - assertThat(parseInt(octets[3])) - .as("fourth octet is 0-255") - .isGreaterThanOrEqualTo(0) - .isLessThanOrEqualTo(255); - } - } - - @Test - public void testIpV4Cidr() { - assertThat(faker.internet().ipV4Cidr().chars().filter(c -> c == '.').count()).isEqualTo(3); - assertThat(faker.internet().ipV4Cidr().chars().filter(c -> c == '/').count()).isEqualTo(1); - - for (int i = 0; i < 1000; i++) { - assertThat(parseInt(faker.internet().ipV4Cidr().split("/")[1])) - .isGreaterThanOrEqualTo(0) - .isLessThan(32); - } - } - - @Test - public void testPrivateIpV4Address() { - String tenDot = "^10\\..+"; - String oneTwoSeven = "^127\\..+"; - String oneSixNine = "^169\\.254\\..+"; - String oneNineTwo = "^192\\.168\\..+"; - String oneSevenTwo = "^172\\.(16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)\\..+"; - - - for (int i = 0; i < 1000; i++) { - String addr = faker.internet().privateIpV4Address(); - assertThat(addr) - .satisfiesAnyOf( - arg -> assertThat(arg).matches(tenDot), - arg -> assertThat(arg).matches(oneTwoSeven), - arg -> assertThat(arg).matches(oneSixNine), - arg -> assertThat(arg).matches(oneNineTwo), - arg -> assertThat(arg).matches(oneSevenTwo) - ); - } - } - - @Test - public void testPublicIpV4Address() { - String tenDot = "^10\\."; - String oneTwoSeven = "^127\\."; - String oneSixNine = "^169\\.254"; - String oneNineTwo = "^192\\.168\\."; - String oneSevenTwo = "^172\\.(16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)\\."; - for (int i = 0; i < 1000; i++) { - String addr = faker.internet().publicIpV4Address(); - assertThat(addr.matches(tenDot)).isEqualTo(false); - assertThat(addr.matches(oneTwoSeven)).isEqualTo(false); - assertThat(addr.matches(oneSixNine)).isEqualTo(false); - assertThat(addr.matches(oneNineTwo)).isEqualTo(false); - assertThat(addr.matches(oneSevenTwo)).isEqualTo(false); - } - } - - @Test - public void testIpV6() { - assertThat(faker.internet().ipV6Address().chars().filter(c -> c == ':').count()).isEqualTo(7); - - for (int i = 0; i < 1000; i++) { - assertThat(faker.internet().ipV6Address()).matches("[0-9a-fA-F]{1,4}(\\:([0-9a-fA-F]{1,4})){1,7}"); - } - } - - @Test - public void testIpV6Cidr() { - assertThat(faker.internet().ipV6Cidr().chars().filter(c -> c == ':').count()).isEqualTo(7); - assertThat(faker.internet().ipV6Cidr().chars().filter(c -> c == '/').count()).isEqualTo(1); - - for (int i = 0; i < 1000; i++) { - assertThat(parseInt(faker.internet().ipV6Cidr().split("/")[1])) - .isGreaterThanOrEqualTo(0) - .isLessThan(128); - } - } - - @TestTemplate - @Repeat(times=10) - public void testSlugWithParams() { - assertThat(faker.internet().slug(ImmutableList.of("a", "b"), "-")).matches("[a-zA-Z]+\\-[a-zA-Z]+"); - } - - @TestTemplate - @Repeat(times=10) - public void testSlug() { - assertThat(faker.internet().slug()).matches("[a-zA-Z]+\\_[a-zA-Z]+"); - } - - @TestTemplate - @Repeat(times=10) - public void testUuid() { - assertThat(faker.internet().uuid()).matches("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"); - } - - @TestTemplate - @Repeat(times=100) - public void testFarsiIDNs() { - // in this case, we're just making sure Farsi doesn't blow up. - // there have been issues with Farsi not being produced. - final Faker f = new Faker(new Locale("fa")); - assertThat(f.internet().domainName()).isNotEmpty(); - assertThat(f.internet().emailAddress()).isNotEmpty(); - assertThat(f.internet().safeEmailAddress()).isNotEmpty(); - assertThat(f.internet().url()).isNotEmpty(); - } - - @Test - public void testUserAgent() { - Internet.UserAgent[] agents = Internet.UserAgent.values(); - for(Internet.UserAgent agent : agents) { - assertThat(faker.internet().userAgent(agent)).isNotEmpty(); - } - - //Test faker.internet().userAgentAny() for random user_agent retrieval. - assertThat(faker.internet().userAgentAny()).isNotEmpty(); - } - - @Test - public void testSlugWithNull(){ - Faker f=new Faker(); - assertThat(f.internet().slug(null, "_")).isNotNull(); - } + @Test + public void testEmailAddress() { + String emailAddress = faker.internet().emailAddress(); + assertThat(EmailValidator.getInstance().isValid(emailAddress)).isEqualTo(true); + } + + @Test + public void testEmailAddressWithLocalPartParameter() { + String emailAddress = faker.internet().emailAddress("john"); + assertThat(emailAddress).startsWith("john@"); + assertThat(EmailValidator.getInstance().isValid(emailAddress)).isEqualTo(true); + } + + @Test + public void testSafeEmailAddress() { + List emails = Lists.newArrayList(); + for (int i = 0; i < 100; i++) { + String emailAddress = faker.internet().safeEmailAddress(); + assertThat(EmailValidator.getInstance().isValid(emailAddress)).isEqualTo(true); + emails.add(emailAddress); + } + final String safeDomain = faker.resolve("internet.safe_email"); + + assertThat(emails) + .as("Should find at least one email from " + safeDomain) + .anyMatch(email -> email.endsWith("@" + safeDomain)); + } + + @Test + public void testSafeEmailAddressWithLocalPartParameter() { + List emails = Lists.newArrayList(); + for (int i = 0; i < 100; i++) { + String emailAddress = faker.internet().safeEmailAddress("john"); + assertThat(emailAddress).startsWith("john@"); + assertThat(EmailValidator.getInstance().isValid(emailAddress)).isEqualTo(true); + emails.add(emailAddress); + } + final String safeDomain = faker.resolve("internet.safe_email"); + + assertThat(emails) + .as("Should find at least one email from " + safeDomain) + .anyMatch(email -> email.endsWith("@" + safeDomain)); + } + + @Test + public void testEmailAddressDoesNotIncludeAccentsInTheLocalPart() { + String emailAddress = faker.internet().emailAddress("áéíóú"); + assertThat(emailAddress).startsWith("aeiou@"); + } + + @Test + public void testSafeEmailAddressDoesNotIncludeAccentsInTheLocalPart() { + String emailAddress = faker.internet().safeEmailAddress("áéíóú"); + assertThat(emailAddress).startsWith("aeiou@"); + } + + @Test + public void testUrl() { + assertThat(faker.internet().url()).matches("www\\.(\\w|-)+\\.\\w+"); + } + + @Test + public void testAvatar() { + assertThat(faker.internet().avatar()).matches("http.*/[^/]+/128.jpg$"); + } + + @Test + public void testImage() { + String imageUrl = faker.internet().image(); + assertThat(imageUrl).matches("^http:\\/\\/lorempixel\\.com(/g)?/\\d{1,4}/\\d{1,4}/\\w+/$"); + } + + @Test + public void testDomainName() { + assertThat(faker.internet().domainName()).matches("[a-z]+\\.\\w{2,4}"); + } + + @Test + public void testDomainWord() { + assertThat(faker.internet().domainWord()).matches("[a-z]+"); + } + + @Test + public void testDomainSuffix() { + assertThat(faker.internet().domainSuffix()).matches("\\w{2,4}"); + } + + @Test + public void testImageWithExplicitParams() { + String imageUrl = faker.internet().image(800, 600, false, "bugs"); + assertThat(imageUrl).matches("^http:\\/\\/lorempixel\\.com/800/600/\\w+/bugs$"); + } + + @Test + public void testPassword() { + assertThat(faker.internet().password()).matches("[a-z\\d]{8,16}"); + } + + @Test + public void testPasswordIncludeDigit() { + assertThat(faker.internet().password()).matches("[a-z\\d]{8,16}"); + assertThat(faker.internet().password(false)).matches("[a-z]{8,16}"); + } + + @Test + public void testPasswordMinLengthMaxLength() { + assertThat(faker.internet().password(10, 25)).matches("[a-z\\d]{10,25}"); + } + + @Test + public void testPasswordMinLengthMaxLengthIncludeUpperCase() { + assertThat(faker.internet().password(1, 2, false)).matches("[a-z\\d]{1,2}"); + assertThat(faker.internet().password(10, 25, true)).matches("[a-zA-Z\\d]{10,25}"); + } + + @Test + public void testPasswordMinLengthMaxLengthIncludeUpperCaseIncludeSpecial() { + assertThat(faker.internet().password(10, 25, false, false)).matches("[a-z\\d]{10,25}"); + assertThat(faker.internet().password(10, 25, false, true)).matches("[a-z\\d!@#$%^&*]{10,25}"); + assertThat(faker.internet().password(10, 25, true, true)).matches("[a-zA-Z\\d!@#$%^&*]{10,25}"); + } + + @Test + public void testPasswordMinLengthMaxLengthIncludeUpperCaseIncludeSpecialIncludeDigit() { + assertThat(faker.internet().password(10, 25, false, false, false)).matches("[a-z]{10,25}"); + assertThat(faker.internet().password(10, 25, false, true, true)) + .matches("[a-z\\d!@#$%^&*]{10,25}"); + assertThat(faker.internet().password(10, 25, true, true, false)) + .matches("[a-zA-Z!@#$%^&*]{10,25}"); + assertThat(faker.internet().password(10, 25, true, true, true)) + .matches("[a-zA-Z\\d!@#$%^&*]{10,25}"); + } + + @Test + public void testMacAddress() { + assertThat(faker.internet().macAddress().chars().filter(c -> c == ':').count()).isEqualTo(5); + assertThat(faker.internet().macAddress("").chars().filter(c -> c == ':').count()).isEqualTo(5); + + assertThat(faker.internet().macAddress("fa:fa:fa")).startsWith("fa:fa:fa"); + assertThat(faker.internet().macAddress("fa:fa:fa").chars().filter(c -> c == ':').count()) + .isEqualTo(5); + + assertThat(faker.internet().macAddress("01:02")).startsWith("01:02"); + assertThat(faker.internet().macAddress("01:02").chars().filter(c -> c == ':').count()) + .isEqualTo(5); + + // loop through 1000 times just to 'run it through the wringer' + for (int i = 0; i < 1000; i++) { + assertThat(faker.internet().macAddress()).matches("[0-9a-fA-F]{2}(\\:([0-9a-fA-F]{1,4})){5}"); + } + } + + @Test + public void testIpV4Address() { + assertThat(faker.internet().ipV4Address().chars().filter(c -> c == '.').count()).isEqualTo(3); + for (int i = 0; i < 100; i++) { + final String[] octets = faker.internet().ipV4Address().split("\\."); + assertThat(parseInt(octets[0])) + .as("first octet is 1-255") + .isGreaterThanOrEqualTo(0) + .isLessThanOrEqualTo(255); + assertThat(parseInt(octets[1])) + .as("second octet is 0-255") + .isGreaterThanOrEqualTo(0) + .isLessThanOrEqualTo(255); + assertThat(parseInt(octets[2])) + .as("third octet is 0-255") + .isGreaterThanOrEqualTo(0) + .isLessThanOrEqualTo(255); + assertThat(parseInt(octets[3])) + .as("fourth octet is 0-255") + .isGreaterThanOrEqualTo(0) + .isLessThanOrEqualTo(255); + } + } + + @Test + public void testIpV4Cidr() { + assertThat(faker.internet().ipV4Cidr().chars().filter(c -> c == '.').count()).isEqualTo(3); + assertThat(faker.internet().ipV4Cidr().chars().filter(c -> c == '/').count()).isEqualTo(1); + + for (int i = 0; i < 1000; i++) { + assertThat(parseInt(faker.internet().ipV4Cidr().split("/")[1])) + .isGreaterThanOrEqualTo(0) + .isLessThan(32); + } + } + + @Test + public void testPrivateIpV4Address() { + String tenDot = "^10\\..+"; + String oneTwoSeven = "^127\\..+"; + String oneSixNine = "^169\\.254\\..+"; + String oneNineTwo = "^192\\.168\\..+"; + String oneSevenTwo = "^172\\.(16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)\\..+"; + + for (int i = 0; i < 1000; i++) { + String addr = faker.internet().privateIpV4Address(); + assertThat(addr) + .satisfiesAnyOf( + arg -> assertThat(arg).matches(tenDot), + arg -> assertThat(arg).matches(oneTwoSeven), + arg -> assertThat(arg).matches(oneSixNine), + arg -> assertThat(arg).matches(oneNineTwo), + arg -> assertThat(arg).matches(oneSevenTwo)); + } + } + + @Test + public void testPublicIpV4Address() { + String tenDot = "^10\\."; + String oneTwoSeven = "^127\\."; + String oneSixNine = "^169\\.254"; + String oneNineTwo = "^192\\.168\\."; + String oneSevenTwo = "^172\\.(16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)\\."; + for (int i = 0; i < 1000; i++) { + String addr = faker.internet().publicIpV4Address(); + assertThat(addr.matches(tenDot)).isEqualTo(false); + assertThat(addr.matches(oneTwoSeven)).isEqualTo(false); + assertThat(addr.matches(oneSixNine)).isEqualTo(false); + assertThat(addr.matches(oneNineTwo)).isEqualTo(false); + assertThat(addr.matches(oneSevenTwo)).isEqualTo(false); + } + } + + @Test + public void testIpV6() { + assertThat(faker.internet().ipV6Address().chars().filter(c -> c == ':').count()).isEqualTo(7); + + for (int i = 0; i < 1000; i++) { + assertThat(faker.internet().ipV6Address()) + .matches("[0-9a-fA-F]{1,4}(\\:([0-9a-fA-F]{1,4})){1,7}"); + } + } + + @Test + public void testIpV6Cidr() { + assertThat(faker.internet().ipV6Cidr().chars().filter(c -> c == ':').count()).isEqualTo(7); + assertThat(faker.internet().ipV6Cidr().chars().filter(c -> c == '/').count()).isEqualTo(1); + + for (int i = 0; i < 1000; i++) { + assertThat(parseInt(faker.internet().ipV6Cidr().split("/")[1])) + .isGreaterThanOrEqualTo(0) + .isLessThan(128); + } + } + + @TestTemplate + @Repeat(times = 10) + public void testSlugWithParams() { + assertThat(faker.internet().slug(ImmutableList.of("a", "b"), "-")) + .matches("[a-zA-Z]+\\-[a-zA-Z]+"); + } + + @TestTemplate + @Repeat(times = 10) + public void testSlug() { + assertThat(faker.internet().slug()).matches("[a-zA-Z]+\\_[a-zA-Z]+"); + } + + @TestTemplate + @Repeat(times = 10) + public void testUuid() { + assertThat(faker.internet().uuid()) + .matches("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"); + } + + @TestTemplate + @Repeat(times = 100) + public void testFarsiIDNs() { + // in this case, we're just making sure Farsi doesn't blow up. + // there have been issues with Farsi not being produced. + final Faker f = new Faker(new Locale("fa")); + assertThat(f.internet().domainName()).isNotEmpty(); + assertThat(f.internet().emailAddress()).isNotEmpty(); + assertThat(f.internet().safeEmailAddress()).isNotEmpty(); + assertThat(f.internet().url()).isNotEmpty(); + } + + @Test + public void testUserAgent() { + Internet.UserAgent[] agents = Internet.UserAgent.values(); + for (Internet.UserAgent agent : agents) { + assertThat(faker.internet().userAgent(agent)).isNotEmpty(); + } + + // Test faker.internet().userAgentAny() for random user_agent retrieval. + assertThat(faker.internet().userAgentAny()).isNotEmpty(); + } + + @Test + public void testSlugWithNull() { + Faker f = new Faker(); + assertThat(f.internet().slug(null, "_")).isNotNull(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/JobTest.java b/src/test/java/org/thejavaguy/javafaker/JobTest.java index 801d6d9..021c47b 100644 --- a/src/test/java/org/thejavaguy/javafaker/JobTest.java +++ b/src/test/java/org/thejavaguy/javafaker/JobTest.java @@ -6,28 +6,28 @@ public class JobTest extends AbstractFakerTest { - @Test - public void field() { - assertThat(faker.job().field()).matches("^[A-Z][A-Za-z-]+$"); - } - - @Test - public void seniority() { - assertThat(faker.job().seniority()).matches("^[A-Z][a-z]+$"); - } - - @Test - public void position() { - assertThat(faker.job().position()).matches("^[A-Z][a-z]+$"); - } - - @Test - public void keySkills() { - assertThat(faker.job().keySkills()).matches("([A-Za-z-]+ ?){1,3}"); - } - - @Test - public void title() { - assertThat(faker.job().title()).matches("([A-Za-z-]+ ?){2,3}"); - } + @Test + public void field() { + assertThat(faker.job().field()).matches("^[A-Z][A-Za-z-]+$"); + } + + @Test + public void seniority() { + assertThat(faker.job().seniority()).matches("^[A-Z][a-z]+$"); + } + + @Test + public void position() { + assertThat(faker.job().position()).matches("^[A-Z][a-z]+$"); + } + + @Test + public void keySkills() { + assertThat(faker.job().keySkills()).matches("([A-Za-z-]+ ?){1,3}"); + } + + @Test + public void title() { + assertThat(faker.job().title()).matches("([A-Za-z-]+ ?){2,3}"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/KaamelottTest.java b/src/test/java/org/thejavaguy/javafaker/KaamelottTest.java index 44de584..39d0f16 100644 --- a/src/test/java/org/thejavaguy/javafaker/KaamelottTest.java +++ b/src/test/java/org/thejavaguy/javafaker/KaamelottTest.java @@ -6,13 +6,14 @@ public class KaamelottTest extends AbstractFakerTest { - @Test - public void testCharacter() { - assertThat(faker.kaamelott().character()).matches("[A-Za-z' -ÇÉàçêèéïîüùú]+"); - } + @Test + public void testCharacter() { + assertThat(faker.kaamelott().character()).matches("[A-Za-z' -ÇÉàçêèéïîüùú]+"); + } - @Test - public void testQuote() { - assertThat(faker.kaamelott().quote()).matches("[-A-Za-z0-9 —ÇÉàçêèéïîüùú;:…\\?\\!\\.’‘'”“,\\[\\]]+"); - } + @Test + public void testQuote() { + assertThat(faker.kaamelott().quote()) + .matches("[-A-Za-z0-9 —ÇÉàçêèéïîüùú;:…\\?\\!\\.’‘'”“,\\[\\]]+"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/LeagueOfLegendsTest.java b/src/test/java/org/thejavaguy/javafaker/LeagueOfLegendsTest.java index dcd7e9f..4baca6e 100644 --- a/src/test/java/org/thejavaguy/javafaker/LeagueOfLegendsTest.java +++ b/src/test/java/org/thejavaguy/javafaker/LeagueOfLegendsTest.java @@ -7,33 +7,33 @@ public class LeagueOfLegendsTest extends AbstractFakerTest { - @Test - public void champion() { - assertThat(faker.leagueOfLegends().champion()).matches("^(\\w+\\.?-?'?\\s?&?\\s?)+$"); - } - - @Test - public void location() { - assertThat(faker.leagueOfLegends().location()).matches("^(\\w+\\s?)+$"); - } - - @Test - public void quote() { - assertFalse(faker.leagueOfLegends().quote().isEmpty()); - } - - @Test - public void summonerSpell() { - assertThat(faker.leagueOfLegends().summonerSpell()).matches("^(\\w+\\s?!?)+$"); - } - - @Test - public void masteries() { - assertThat(faker.leagueOfLegends().masteries()).matches("^(\\w+\\s?'?)+$"); - } - - @Test - public void rank() { - assertThat(faker.leagueOfLegends().rank()).matches("^\\w+(\\s[IV]+)?$"); - } + @Test + public void champion() { + assertThat(faker.leagueOfLegends().champion()).matches("^(\\w+\\.?-?'?\\s?&?\\s?)+$"); + } + + @Test + public void location() { + assertThat(faker.leagueOfLegends().location()).matches("^(\\w+\\s?)+$"); + } + + @Test + public void quote() { + assertFalse(faker.leagueOfLegends().quote().isEmpty()); + } + + @Test + public void summonerSpell() { + assertThat(faker.leagueOfLegends().summonerSpell()).matches("^(\\w+\\s?!?)+$"); + } + + @Test + public void masteries() { + assertThat(faker.leagueOfLegends().masteries()).matches("^(\\w+\\s?'?)+$"); + } + + @Test + public void rank() { + assertThat(faker.leagueOfLegends().rank()).matches("^\\w+(\\s[IV]+)?$"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/LebowskiTest.java b/src/test/java/org/thejavaguy/javafaker/LebowskiTest.java index b782622..4bd8a9b 100644 --- a/src/test/java/org/thejavaguy/javafaker/LebowskiTest.java +++ b/src/test/java/org/thejavaguy/javafaker/LebowskiTest.java @@ -5,18 +5,18 @@ import org.junit.jupiter.api.Test; public class LebowskiTest extends AbstractFakerTest { - @Test - public void actor() { - assertThat(faker.lebowski().actor()).matches("^([\\w]+ ?){1,3}$"); - } + @Test + public void actor() { + assertThat(faker.lebowski().actor()).matches("^([\\w]+ ?){1,3}$"); + } - @Test - public void character() { - assertThat(faker.lebowski().character()).matches("^([\\w]+ ?){1,3}$"); - } + @Test + public void character() { + assertThat(faker.lebowski().character()).matches("^([\\w]+ ?){1,3}$"); + } - @Test - public void quote() { - assertThat(faker.lebowski().quote()).matches("^([\\w.,!?'-]+ ?)+$"); - } + @Test + public void quote() { + assertThat(faker.lebowski().quote()).matches("^([\\w.,!?'-]+ ?)+$"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/LordOfTheRingsTest.java b/src/test/java/org/thejavaguy/javafaker/LordOfTheRingsTest.java index b4bb6e2..b6e5ed9 100644 --- a/src/test/java/org/thejavaguy/javafaker/LordOfTheRingsTest.java +++ b/src/test/java/org/thejavaguy/javafaker/LordOfTheRingsTest.java @@ -9,13 +9,13 @@ */ public class LordOfTheRingsTest extends AbstractFakerTest { - @Test - public void character() { - assertThat(faker.lordOfTheRings().character()).matches("(?U)([\\w ]+ ?)+"); - } + @Test + public void character() { + assertThat(faker.lordOfTheRings().character()).matches("(?U)([\\w ]+ ?)+"); + } - @Test - public void location() { - assertThat(faker.lordOfTheRings().location()).matches("(?U)([\\w'\\- ]+ ?)+"); - } + @Test + public void location() { + assertThat(faker.lordOfTheRings().location()).matches("(?U)([\\w'\\- ]+ ?)+"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/LoremTest.java b/src/test/java/org/thejavaguy/javafaker/LoremTest.java index e0f9d62..374b9cb 100644 --- a/src/test/java/org/thejavaguy/javafaker/LoremTest.java +++ b/src/test/java/org/thejavaguy/javafaker/LoremTest.java @@ -7,97 +7,97 @@ public class LoremTest extends AbstractFakerTest { - @Test - public void shouldCreateFixedLengthString() { - assertEquals(10, faker.lorem().fixedString(10).length()); - assertEquals(50, faker.lorem().fixedString(50).length()); - assertEquals(0, faker.lorem().fixedString(0).length()); - assertEquals(0, faker.lorem().fixedString(-1).length()); - } - - @Test - public void wordShouldNotBeNullOrEmpty() { - assertThat(faker.lorem().word()).isNotEmpty(); - } - - @Test - public void testCharacter() { - assertThat(String.valueOf(faker.lorem().character())).matches("[a-z\\d]{1}"); - } - - @Test - public void testCharacterIncludeUpperCase() { - assertThat(String.valueOf(faker.lorem().character(false))).matches("[a-z\\d]{1}"); - assertThat(String.valueOf(faker.lorem().character(true))).matches("[a-zA-Z\\d]{1}"); - } - - @Test - public void testCharacters() { - assertThat(faker.lorem().characters()).matches("[a-z\\d]{255}"); - } - - @Test - public void testCharactersIncludeUpperCase() { - assertThat(faker.lorem().characters(false)).matches("[a-z\\d]{255}"); - assertThat(faker.lorem().characters(true)).matches("[a-zA-Z\\d]{255}"); - } - - @Test - public void testCharactersWithLength() { - assertThat(faker.lorem().characters(2)).matches("[a-z\\d]{2}"); - assertThat(faker.lorem().characters(500)).matches("[a-z\\d]{500}"); - assertThat(faker.lorem().characters(0)).isEmpty(); - assertThat(faker.lorem().characters(-1)).isEmpty(); - } - - @Test - public void testCharactersWithLengthIncludeUppercase() { - assertThat(faker.lorem().characters(2, false)).matches("[a-z\\d]{2}"); - assertThat(faker.lorem().characters(500, false)).matches("[a-z\\d]{500}"); - assertThat(faker.lorem().characters(2, true)).matches("[a-zA-Z\\d]{2}"); - assertThat(faker.lorem().characters(500, true)).matches("[a-zA-Z\\d]{500}"); - assertThat(faker.lorem().characters(0, false)).isEmpty(); - assertThat(faker.lorem().characters(-1, true)).isEmpty(); - } - - @Test - public void testCharactersMinimumMaximumLength() { - assertThat(faker.lorem().characters(1, 10)).matches("[a-z\\d]{1,10}"); - } - - @Test - public void testCharactersMinimumMaximumLengthIncludeUppercase() { - assertThat(faker.lorem().characters(1, 10, true)).matches("[a-zA-Z\\d]{1,10}"); - } - - @Test - public void testCharactersMinimumMaximumLengthIncludeUppercaseIncludeDigit() { - assertThat(faker.lorem().characters(1, 10, false, false)).matches("[a-zA-Z]{1,10}"); - assertThat(faker.lorem().characters(1, 10, true, true)).matches("[a-zA-Z\\d]{1,10}"); - } - - @Test - public void testSentence() { - assertThat(faker.lorem().sentence()).matches("(\\w+\\s?){4,10}\\."); - } - - @Test - public void testSentenceWithWordCount() { - assertThat(faker.lorem().sentence(10)).matches("(\\w+\\s?){11,17}\\."); - } - - @Test - public void testSentenceWithWordCountAndRandomWordsToAdd() { - assertThat(faker.lorem().sentence(10, 10)).matches("(\\w+\\s?){10,20}\\."); - } - - @Test - public void testSentenceFixedNumberOfWords() { - assertThat(faker.lorem().sentence(10, 0)).matches("(\\w+\\s?){10}\\."); - } - - @Test - public void testWords() { - assertThat(faker.lorem().words()).hasSizeGreaterThanOrEqualTo(1); - } + @Test + public void shouldCreateFixedLengthString() { + assertEquals(10, faker.lorem().fixedString(10).length()); + assertEquals(50, faker.lorem().fixedString(50).length()); + assertEquals(0, faker.lorem().fixedString(0).length()); + assertEquals(0, faker.lorem().fixedString(-1).length()); + } + + @Test + public void wordShouldNotBeNullOrEmpty() { + assertThat(faker.lorem().word()).isNotEmpty(); + } + + @Test + public void testCharacter() { + assertThat(String.valueOf(faker.lorem().character())).matches("[a-z\\d]{1}"); + } + + @Test + public void testCharacterIncludeUpperCase() { + assertThat(String.valueOf(faker.lorem().character(false))).matches("[a-z\\d]{1}"); + assertThat(String.valueOf(faker.lorem().character(true))).matches("[a-zA-Z\\d]{1}"); + } + + @Test + public void testCharacters() { + assertThat(faker.lorem().characters()).matches("[a-z\\d]{255}"); + } + + @Test + public void testCharactersIncludeUpperCase() { + assertThat(faker.lorem().characters(false)).matches("[a-z\\d]{255}"); + assertThat(faker.lorem().characters(true)).matches("[a-zA-Z\\d]{255}"); + } + + @Test + public void testCharactersWithLength() { + assertThat(faker.lorem().characters(2)).matches("[a-z\\d]{2}"); + assertThat(faker.lorem().characters(500)).matches("[a-z\\d]{500}"); + assertThat(faker.lorem().characters(0)).isEmpty(); + assertThat(faker.lorem().characters(-1)).isEmpty(); + } + + @Test + public void testCharactersWithLengthIncludeUppercase() { + assertThat(faker.lorem().characters(2, false)).matches("[a-z\\d]{2}"); + assertThat(faker.lorem().characters(500, false)).matches("[a-z\\d]{500}"); + assertThat(faker.lorem().characters(2, true)).matches("[a-zA-Z\\d]{2}"); + assertThat(faker.lorem().characters(500, true)).matches("[a-zA-Z\\d]{500}"); + assertThat(faker.lorem().characters(0, false)).isEmpty(); + assertThat(faker.lorem().characters(-1, true)).isEmpty(); + } + + @Test + public void testCharactersMinimumMaximumLength() { + assertThat(faker.lorem().characters(1, 10)).matches("[a-z\\d]{1,10}"); + } + + @Test + public void testCharactersMinimumMaximumLengthIncludeUppercase() { + assertThat(faker.lorem().characters(1, 10, true)).matches("[a-zA-Z\\d]{1,10}"); + } + + @Test + public void testCharactersMinimumMaximumLengthIncludeUppercaseIncludeDigit() { + assertThat(faker.lorem().characters(1, 10, false, false)).matches("[a-zA-Z]{1,10}"); + assertThat(faker.lorem().characters(1, 10, true, true)).matches("[a-zA-Z\\d]{1,10}"); + } + + @Test + public void testSentence() { + assertThat(faker.lorem().sentence()).matches("(\\w+\\s?){4,10}\\."); + } + + @Test + public void testSentenceWithWordCount() { + assertThat(faker.lorem().sentence(10)).matches("(\\w+\\s?){11,17}\\."); + } + + @Test + public void testSentenceWithWordCountAndRandomWordsToAdd() { + assertThat(faker.lorem().sentence(10, 10)).matches("(\\w+\\s?){10,20}\\."); + } + + @Test + public void testSentenceFixedNumberOfWords() { + assertThat(faker.lorem().sentence(10, 0)).matches("(\\w+\\s?){10}\\."); + } + + @Test + public void testWords() { + assertThat(faker.lorem().words()).hasSizeGreaterThanOrEqualTo(1); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/MatzTest.java b/src/test/java/org/thejavaguy/javafaker/MatzTest.java index 056bfb3..b98f93d 100644 --- a/src/test/java/org/thejavaguy/javafaker/MatzTest.java +++ b/src/test/java/org/thejavaguy/javafaker/MatzTest.java @@ -6,8 +6,8 @@ public class MatzTest extends AbstractFakerTest { - @Test - public void quote() { - assertThat(faker.matz().quote()).isNotEmpty(); - } + @Test + public void quote() { + assertThat(faker.matz().quote()).isNotEmpty(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/MedicalTest.java b/src/test/java/org/thejavaguy/javafaker/MedicalTest.java index c5e546e..93284f5 100644 --- a/src/test/java/org/thejavaguy/javafaker/MedicalTest.java +++ b/src/test/java/org/thejavaguy/javafaker/MedicalTest.java @@ -6,25 +6,23 @@ public class MedicalTest extends AbstractFakerTest { - @Test - public void testMedicineName() { - assertThat(faker.medical().medicineName()).isNotBlank(); - } - - @Test - public void testDiseaseName() { - assertThat(faker.medical().diseaseName()).isNotBlank(); - } - - @Test - public void testHospitalName() { - assertThat(faker.medical().hospitalName()).isNotBlank(); - } - - @Test - public void testSymptom() { - assertThat(faker.medical().symptoms()).isNotBlank(); - } - - + @Test + public void testMedicineName() { + assertThat(faker.medical().medicineName()).isNotBlank(); + } + + @Test + public void testDiseaseName() { + assertThat(faker.medical().diseaseName()).isNotBlank(); + } + + @Test + public void testHospitalName() { + assertThat(faker.medical().hospitalName()).isNotBlank(); + } + + @Test + public void testSymptom() { + assertThat(faker.medical().symptoms()).isNotBlank(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/MountainTest.java b/src/test/java/org/thejavaguy/javafaker/MountainTest.java index 728c220..c0bf346 100644 --- a/src/test/java/org/thejavaguy/javafaker/MountainTest.java +++ b/src/test/java/org/thejavaguy/javafaker/MountainTest.java @@ -5,15 +5,15 @@ import org.junit.jupiter.api.Test; public class MountainTest extends AbstractFakerTest { - @Test - public void testMountainName() { - String mountainName = faker.mountain().name(); - assertThat(mountainName).isNotEmpty(); - } + @Test + public void testMountainName() { + String mountainName = faker.mountain().name(); + assertThat(mountainName).isNotEmpty(); + } - @Test - public void testMountainLeague() { - String mountainLeague = faker.mountain().range(); - assertThat(mountainLeague).isNotEmpty(); - } + @Test + public void testMountainLeague() { + String mountainLeague = faker.mountain().range(); + assertThat(mountainLeague).isNotEmpty(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/MusicTest.java b/src/test/java/org/thejavaguy/javafaker/MusicTest.java index 9300278..74f5e4d 100644 --- a/src/test/java/org/thejavaguy/javafaker/MusicTest.java +++ b/src/test/java/org/thejavaguy/javafaker/MusicTest.java @@ -6,23 +6,23 @@ public class MusicTest extends AbstractFakerTest { - @Test - public void instrument() { - assertThat(faker.music().instrument()).matches("\\w+ ?\\w+"); - } + @Test + public void instrument() { + assertThat(faker.music().instrument()).matches("\\w+ ?\\w+"); + } - @Test - public void key() { - assertThat(faker.music().key()).matches("([A-Z])+(b|#){0,1}"); - } + @Test + public void key() { + assertThat(faker.music().key()).matches("([A-Z])+(b|#){0,1}"); + } - @Test - public void chord() { - assertThat(faker.music().chord()).matches("([A-Z])+(b|#){0,1}+(-?[a-zA-Z0-9]{0,4})"); - } + @Test + public void chord() { + assertThat(faker.music().chord()).matches("([A-Z])+(b|#){0,1}+(-?[a-zA-Z0-9]{0,4})"); + } - @Test - public void genre() { - assertThat(faker.music().genre()).matches("[[ -]?\\w+]+"); - } + @Test + public void genre() { + assertThat(faker.music().genre()).matches("[[ -]?\\w+]+"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/NameTest.java b/src/test/java/org/thejavaguy/javafaker/NameTest.java index bcbf203..cb12f6f 100644 --- a/src/test/java/org/thejavaguy/javafaker/NameTest.java +++ b/src/test/java/org/thejavaguy/javafaker/NameTest.java @@ -8,74 +8,73 @@ import org.junit.jupiter.api.TestTemplate; import org.thejavaguy.javafaker.repeating.Repeat; - -public class NameTest extends AbstractFakerTest{ - - @Test - public void testName() { - assertThat(faker.name().name()).matches("([\\w']+\\.?( )?){2,3}"); - } - - @Test - public void testNameWithMiddle() { - assertThat(faker.name().nameWithMiddle()).matches("([\\w']+\\.?( )?){3,4}"); - } - - @TestTemplate @Repeat(times = 10) - public void testNameWithMiddleDoesNotHaveRepeatedName() { - String nameWithMiddle = faker.name().nameWithMiddle(); - String[] splitNames = nameWithMiddle.split(" "); - String firstName = splitNames[0]; - String middleName = splitNames[1]; - assertThat(firstName).isNotEqualTo(middleName); - } - - @Test - public void testFullName() { - assertThat(faker.name().fullName()).matches("([\\w']+\\.?( )?){2,4}"); - } - - @Test - public void testFirstName() { - assertThat(faker.name().firstName()).matches("\\w+"); - } - - @Test - public void testLastName() { - assertThat(faker.name().lastName()).matches("[A-Za-z']+"); - } - - @Test - public void testPrefix() { - assertThat(faker.name().prefix()).matches("\\w+\\.?"); - } - - @Test - public void testSuffix() { - assertThat(faker.name().suffix()).matches("\\w+\\.?"); - } - - @Test - public void testTitle() { - assertThat(faker.name().title()).matches("(\\w+\\.?( )?){3}"); - } - - @Test - public void testUsername() { - assertThat(faker.name().username()).matches("^(\\w+)\\.(\\w+)$"); - } - - @Test - public void testUsernameWithSpaces() { - final Name name = spy(new Name(faker)); - doReturn("Compound Name").when(name).firstName(); - doReturn(name).when(faker).name(); - assertThat(faker.name().username()).matches("^(\\w+)\\.(\\w+)$"); - } - - @Test - public void testBloodGroup() { - assertThat(faker.name().bloodGroup()).matches("(A|B|AB|O)[+-]"); - } - +public class NameTest extends AbstractFakerTest { + + @Test + public void testName() { + assertThat(faker.name().name()).matches("([\\w']+\\.?( )?){2,3}"); + } + + @Test + public void testNameWithMiddle() { + assertThat(faker.name().nameWithMiddle()).matches("([\\w']+\\.?( )?){3,4}"); + } + + @TestTemplate + @Repeat(times = 10) + public void testNameWithMiddleDoesNotHaveRepeatedName() { + String nameWithMiddle = faker.name().nameWithMiddle(); + String[] splitNames = nameWithMiddle.split(" "); + String firstName = splitNames[0]; + String middleName = splitNames[1]; + assertThat(firstName).isNotEqualTo(middleName); + } + + @Test + public void testFullName() { + assertThat(faker.name().fullName()).matches("([\\w']+\\.?( )?){2,4}"); + } + + @Test + public void testFirstName() { + assertThat(faker.name().firstName()).matches("\\w+"); + } + + @Test + public void testLastName() { + assertThat(faker.name().lastName()).matches("[A-Za-z']+"); + } + + @Test + public void testPrefix() { + assertThat(faker.name().prefix()).matches("\\w+\\.?"); + } + + @Test + public void testSuffix() { + assertThat(faker.name().suffix()).matches("\\w+\\.?"); + } + + @Test + public void testTitle() { + assertThat(faker.name().title()).matches("(\\w+\\.?( )?){3}"); + } + + @Test + public void testUsername() { + assertThat(faker.name().username()).matches("^(\\w+)\\.(\\w+)$"); + } + + @Test + public void testUsernameWithSpaces() { + final Name name = spy(new Name(faker)); + doReturn("Compound Name").when(name).firstName(); + doReturn(name).when(faker).name(); + assertThat(faker.name().username()).matches("^(\\w+)\\.(\\w+)$"); + } + + @Test + public void testBloodGroup() { + assertThat(faker.name().bloodGroup()).matches("(A|B|AB|O)[+-]"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/NationTest.java b/src/test/java/org/thejavaguy/javafaker/NationTest.java index 83fcd4f..8ba6b97 100644 --- a/src/test/java/org/thejavaguy/javafaker/NationTest.java +++ b/src/test/java/org/thejavaguy/javafaker/NationTest.java @@ -6,28 +6,27 @@ public class NationTest extends AbstractFakerTest { - @Test - public void nationality() { - assertThat(faker.nation().nationality()).matches("\\P{Cc}+"); - } - - @Test - public void language() { - assertThat(faker.nation().language()).matches("[A-Za-z ]+"); - } - - @Test - public void capitalCity() { - assertThat(faker.nation().capitalCity()).matches("[A-Za-z .'()-]+"); - } - - @Test - public void flag() { - String flag = faker.nation().flag(); - - // all utf8 emoji flags are at least 4 characters long and start with the same char - assertThat(flag.length()).isGreaterThanOrEqualTo(4); - assertThat(flag.charAt(0)).isEqualTo('\uD83C'); - } - + @Test + public void nationality() { + assertThat(faker.nation().nationality()).matches("\\P{Cc}+"); + } + + @Test + public void language() { + assertThat(faker.nation().language()).matches("[A-Za-z ]+"); + } + + @Test + public void capitalCity() { + assertThat(faker.nation().capitalCity()).matches("[A-Za-z .'()-]+"); + } + + @Test + public void flag() { + String flag = faker.nation().flag(); + + // all utf8 emoji flags are at least 4 characters long and start with the same char + assertThat(flag.length()).isGreaterThanOrEqualTo(4); + assertThat(flag.charAt(0)).isEqualTo('\uD83C'); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/NumberTest.java b/src/test/java/org/thejavaguy/javafaker/NumberTest.java index 38a46e6..b996d3a 100644 --- a/src/test/java/org/thejavaguy/javafaker/NumberTest.java +++ b/src/test/java/org/thejavaguy/javafaker/NumberTest.java @@ -2,12 +2,14 @@ import static org.assertj.core.api.Assertions.assertThat; +import com.google.common.base.Function; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; import java.math.BigDecimal; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicLong; - import org.apache.commons.lang3.tuple.Pair; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestTemplate; @@ -15,335 +17,369 @@ import org.slf4j.LoggerFactory; import org.thejavaguy.javafaker.repeating.Repeat; -import com.google.common.base.Function; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; - public class NumberTest extends AbstractFakerTest { - private static final Logger logger = LoggerFactory.getLogger(NumberTest.class); - public static final int RANDOMIZATION_QUALITY_RANGE_END = 1000; - public static final int RANDOMIZATION_QUALITY_RANGE_STEP = 25; - private static final int RANDOMIZATION_QUALITY_RANGE_START = RANDOMIZATION_QUALITY_RANGE_STEP; - public static final int RANDOMIZATION_TESTS_MAX_NUMBERS_TO_GET = 1000; - - final double individualRunGtPercentUnique= 0.8; - final double percentRunsGtUniquePercentage = 0.90; - - @Test - public void testRandomDigit() { - Set nums = Sets.newHashSet(); - for (int i = 0; i < 1000; ++i) { - int value = faker.number().randomDigit(); - assertThat(value).isLessThanOrEqualTo(9); - assertThat(value).isGreaterThanOrEqualTo(0); - nums.add(value); - } - assertThat(nums).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); - } - - @Test - public void testRandomDigitNotZero() { - Set nums = Sets.newHashSet(); - for (int i = 0; i < 1000; ++i) { - int value = faker.number().randomDigitNotZero(); - assertThat(value).isLessThanOrEqualTo(9); - assertThat(value).isGreaterThan(0); - nums.add(value); - } - assertThat(nums).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9); + private static final Logger logger = LoggerFactory.getLogger(NumberTest.class); + public static final int RANDOMIZATION_QUALITY_RANGE_END = 1000; + public static final int RANDOMIZATION_QUALITY_RANGE_STEP = 25; + private static final int RANDOMIZATION_QUALITY_RANGE_START = RANDOMIZATION_QUALITY_RANGE_STEP; + public static final int RANDOMIZATION_TESTS_MAX_NUMBERS_TO_GET = 1000; + + final double individualRunGtPercentUnique = 0.8; + final double percentRunsGtUniquePercentage = 0.90; + + @Test + public void testRandomDigit() { + Set nums = Sets.newHashSet(); + for (int i = 0; i < 1000; ++i) { + int value = faker.number().randomDigit(); + assertThat(value).isLessThanOrEqualTo(9); + assertThat(value).isGreaterThanOrEqualTo(0); + nums.add(value); } - - @Test - public void testRandomNumber() { - long value = faker.number().randomNumber(); - assertThat(value).isLessThan(Long.MAX_VALUE); - } - - @Test - public void testRandomNumberWithSingleDigitStrict() { - for (int i = 0; i < 100; ++i) { - long value = faker.number().randomNumber(1, true); - assertThat(value).isLessThan(10L); - assertThat(value).isGreaterThanOrEqualTo(0L); - } + assertThat(nums).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); + } + + @Test + public void testRandomDigitNotZero() { + Set nums = Sets.newHashSet(); + for (int i = 0; i < 1000; ++i) { + int value = faker.number().randomDigitNotZero(); + assertThat(value).isLessThanOrEqualTo(9); + assertThat(value).isGreaterThan(0); + nums.add(value); } - - @Test - public void testRandomNumberWithZeroDigitsStrict() { - for (int i = 0; i < 100; ++i) { - long value = faker.number().randomNumber(0, true); - assertThat(value).isEqualTo(0L); - } + assertThat(nums).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9); + } + + @Test + public void testRandomNumber() { + long value = faker.number().randomNumber(); + assertThat(value).isLessThan(Long.MAX_VALUE); + } + + @Test + public void testRandomNumberWithSingleDigitStrict() { + for (int i = 0; i < 100; ++i) { + long value = faker.number().randomNumber(1, true); + assertThat(value).isLessThan(10L); + assertThat(value).isGreaterThanOrEqualTo(0L); } + } - @Test - public void testRandomNumberWithGivenDigitsStrict() { - for (int i = 1; i < 9; ++i) { - for (int x = 0; x < 100; ++x) { - long value = faker.number().randomNumber(i, true); - String stringValue = String.valueOf(value); - assertThat(stringValue.length()).isEqualTo(i); - } - } + @Test + public void testRandomNumberWithZeroDigitsStrict() { + for (int i = 0; i < 100; ++i) { + long value = faker.number().randomNumber(0, true); + assertThat(value).isEqualTo(0L); } - - @Test - public void testRandomDouble() { - for (int i = 1; i < 5; ++i) { - for (int x = 0; x < 100; ++x) { - double value = faker.number().randomDouble(i, 1, 1000); - String strVal = BigDecimal.valueOf(value).stripTrailingZeros().toString(); - if (strVal.contains(".") && !strVal.contains("+")) { - int ind = strVal.indexOf("."); - assertThat(strVal.length() - ind - 1).isLessThanOrEqualTo(i); - } - } - } + } + + @Test + public void testRandomNumberWithGivenDigitsStrict() { + for (int i = 1; i < 9; ++i) { + for (int x = 0; x < 100; ++x) { + long value = faker.number().randomNumber(i, true); + String stringValue = String.valueOf(value); + assertThat(stringValue.length()).isEqualTo(i); + } } - - @Test - public void testNumberBetween() { - for (int i = 1; i < 100; ++i) { - int v = faker.number().numberBetween(0, i); - assertThat(v).isLessThanOrEqualTo(i); - assertThat(v).isGreaterThanOrEqualTo(0); + } + + @Test + public void testRandomDouble() { + for (int i = 1; i < 5; ++i) { + for (int x = 0; x < 100; ++x) { + double value = faker.number().randomDouble(i, 1, 1000); + String strVal = BigDecimal.valueOf(value).stripTrailingZeros().toString(); + if (strVal.contains(".") && !strVal.contains("+")) { + int ind = strVal.indexOf("."); + assertThat(strVal.length() - ind - 1).isLessThanOrEqualTo(i); } - - for (long i = 1L; i < 100L; ++i) { - long v = faker.number().numberBetween(0, i); - assertThat(v).isLessThanOrEqualTo(i); - assertThat(v).isGreaterThanOrEqualTo(0L); - } - - int min1 = 1; - long v1 = faker.number().numberBetween(min1, 980000000L); - assertThat(v1).isGreaterThan((long) min1); - assertThat(v1).isLessThan(980000000L); + } } - - @TestTemplate - @Repeat(times = 100) - public void testLongNumberBetweenRepeated() { - long low = 1; - long high = 10; - long v = faker.number().numberBetween(low, high); - assertThat(v).isLessThan(high); - assertThat(v).isGreaterThanOrEqualTo(low); + } + + @Test + public void testNumberBetween() { + for (int i = 1; i < 100; ++i) { + int v = faker.number().numberBetween(0, i); + assertThat(v).isLessThanOrEqualTo(i); + assertThat(v).isGreaterThanOrEqualTo(0); } - @TestTemplate - @Repeat(times = 100) - public void testIntNumberBetweenRepeated() { - int low = 1; - int high = 10; - int v = faker.number().numberBetween(low, high); - assertThat(v).isLessThan(high); - assertThat(v).isGreaterThanOrEqualTo(low); + for (long i = 1L; i < 100L; ++i) { + long v = faker.number().numberBetween(0, i); + assertThat(v).isLessThanOrEqualTo(i); + assertThat(v).isGreaterThanOrEqualTo(0L); } - @Test - public void testNumberBetweenOneAndThree() { - Set nums = Sets.newHashSet(); - final int lowerLimit = 0; - final int upperLimit = 3; - for (int i = 0; i < 1000; ++i) { - int value = faker.number().numberBetween(lowerLimit, upperLimit); - assertThat(value).isLessThan(upperLimit); - assertThat(value).isGreaterThanOrEqualTo(lowerLimit); - nums.add(value); - } - assertThat(nums).containsExactly(0, 1, 2); + int min1 = 1; + long v1 = faker.number().numberBetween(min1, 980000000L); + assertThat(v1).isGreaterThan((long) min1); + assertThat(v1).isLessThan(980000000L); + } + + @TestTemplate + @Repeat(times = 100) + public void testLongNumberBetweenRepeated() { + long low = 1; + long high = 10; + long v = faker.number().numberBetween(low, high); + assertThat(v).isLessThan(high); + assertThat(v).isGreaterThanOrEqualTo(low); + } + + @TestTemplate + @Repeat(times = 100) + public void testIntNumberBetweenRepeated() { + int low = 1; + int high = 10; + int v = faker.number().numberBetween(low, high); + assertThat(v).isLessThan(high); + assertThat(v).isGreaterThanOrEqualTo(low); + } + + @Test + public void testNumberBetweenOneAndThree() { + Set nums = Sets.newHashSet(); + final int lowerLimit = 0; + final int upperLimit = 3; + for (int i = 0; i < 1000; ++i) { + int value = faker.number().numberBetween(lowerLimit, upperLimit); + assertThat(value).isLessThan(upperLimit); + assertThat(value).isGreaterThanOrEqualTo(lowerLimit); + nums.add(value); } - - @Test - public void testLongBetweenOneAndThree() { - Set nums = Sets.newHashSet(); - final long lowerLimit = 0; - final long upperLimit = 3; - for (int i = 0; i < 1000; ++i) { - long value = faker.number().numberBetween(lowerLimit, upperLimit); - assertThat(value).isLessThan(upperLimit); - assertThat(value).isGreaterThanOrEqualTo(lowerLimit); - nums.add(value); - } - assertThat(nums).containsExactly(0L, 1L, 2L); + assertThat(nums).containsExactly(0, 1, 2); + } + + @Test + public void testLongBetweenOneAndThree() { + Set nums = Sets.newHashSet(); + final long lowerLimit = 0; + final long upperLimit = 3; + for (int i = 0; i < 1000; ++i) { + long value = faker.number().numberBetween(lowerLimit, upperLimit); + assertThat(value).isLessThan(upperLimit); + assertThat(value).isGreaterThanOrEqualTo(lowerLimit); + nums.add(value); } - - @Test - public void numberBetweenIntIntZeroMinMax() { - assertThat(faker.number().numberBetween(0, 0)).as("Calling numberBetween with min==max yields min, with 0").isEqualTo(0); - assertThat(faker.number().numberBetween(2, 2)).as("Calling numberBetween with min==max yields min").isEqualTo(2); - } - - @Test - public void numberBetweenLongLongZeroMinMax() { - assertThat(faker.number().numberBetween(0L, 0L)).as("Calling numberBetween with min==max yields min, with 0").isEqualTo(0L); - assertThat(faker.number().numberBetween(2L, 2L)).as("Calling numberBetween with min==max yields min").isEqualTo(2L); - } - - /** - * Given a number of min/max ranges - * for each min/max range, call {@link Number#randomDouble(int, int, int)} with min/max 'n' times - * calculate the uniqueness for that given min/max range. - * For all 'uniqueness' values - * verify the percentage of 'uniqueness' ratios over 80% is 90%. - * - * This isn't perfect but it ensures a pretty good degree of uniqueness in the random number generation. - */ - @Test - public void randomDoubleRandomizationQuality() { - Function, Double> minMaxRangeToUniquePercentageFunction = minMax -> { - final int min = minMax.getLeft().intValue(), max = minMax.getRight().intValue(); - long numbersToGet = calculateNumbersToGet(min, max); - - return uniquePercentageOfResults(numbersToGet, () -> faker.number().randomDouble(0, min, max)); + assertThat(nums).containsExactly(0L, 1L, 2L); + } + + @Test + public void numberBetweenIntIntZeroMinMax() { + assertThat(faker.number().numberBetween(0, 0)) + .as("Calling numberBetween with min==max yields min, with 0") + .isEqualTo(0); + assertThat(faker.number().numberBetween(2, 2)) + .as("Calling numberBetween with min==max yields min") + .isEqualTo(2); + } + + @Test + public void numberBetweenLongLongZeroMinMax() { + assertThat(faker.number().numberBetween(0L, 0L)) + .as("Calling numberBetween with min==max yields min, with 0") + .isEqualTo(0L); + assertThat(faker.number().numberBetween(2L, 2L)) + .as("Calling numberBetween with min==max yields min") + .isEqualTo(2L); + } + + /** + * Given a number of min/max ranges for each min/max range, call {@link Number#randomDouble(int, + * int, int)} with min/max 'n' times calculate the uniqueness for that given min/max range. For + * all 'uniqueness' values verify the percentage of 'uniqueness' ratios over 80% is 90%. + * + *

This isn't perfect but it ensures a pretty good degree of uniqueness in the random number + * generation. + */ + @Test + public void randomDoubleRandomizationQuality() { + Function, Double> minMaxRangeToUniquePercentageFunction = + minMax -> { + final int min = minMax.getLeft().intValue(), max = minMax.getRight().intValue(); + long numbersToGet = calculateNumbersToGet(min, max); + + return uniquePercentageOfResults( + numbersToGet, () -> faker.number().randomDouble(0, min, max)); }; - final double percentGreaterThan80Percent = randomizationQualityTest(individualRunGtPercentUnique, minMaxRangeToUniquePercentageFunction); - assertThat(percentGreaterThan80Percent).as("Percentage of runs > 80% unique is gte 90%").isGreaterThanOrEqualTo(percentRunsGtUniquePercentage); - - // this covers Issue # 121, the number of times the function is called with the MIN/MAX values here - // is RANDOMIZATION_TESTS_MAX_NUMBERS_TO_GET - final double extremeRunUniquePercent = minMaxRangeToUniquePercentageFunction.apply(Pair.of((long) Integer.MIN_VALUE, (long) Integer.MAX_VALUE)); - assertThat(extremeRunUniquePercent).as("Percentage of extreme runs > 80%").isGreaterThanOrEqualTo(individualRunGtPercentUnique); - } - - /** - * Given a number of min/max ranges - * for each min/max range, call numberBetween with min/max 'n' times - * calculate the uniqueness for that given min/max range. - * For all 'uniqueness' values - * verify the percentage of 'uniqueness' ratios over 80% is 90%. - * - * This isn't perfect but it ensures a pretty good degree of uniqueness in the random number generation. - */ - @Test - public void numberBetweenIntIntRandomizationQuality() { - Function, Double> minMaxRangeToUniquePercentageFunction = minMax -> { - final int min = minMax.getLeft().intValue(); - final int max = minMax.getRight().intValue(); - long numbersToGet = calculateNumbersToGet(min, max); - - return uniquePercentageOfResults(numbersToGet, () -> faker.number().numberBetween(min, max)); + final double percentGreaterThan80Percent = + randomizationQualityTest( + individualRunGtPercentUnique, minMaxRangeToUniquePercentageFunction); + assertThat(percentGreaterThan80Percent) + .as("Percentage of runs > 80% unique is gte 90%") + .isGreaterThanOrEqualTo(percentRunsGtUniquePercentage); + + // this covers Issue # 121, the number of times the function is called with the MIN/MAX values + // here + // is RANDOMIZATION_TESTS_MAX_NUMBERS_TO_GET + final double extremeRunUniquePercent = + minMaxRangeToUniquePercentageFunction.apply( + Pair.of((long) Integer.MIN_VALUE, (long) Integer.MAX_VALUE)); + assertThat(extremeRunUniquePercent) + .as("Percentage of extreme runs > 80%") + .isGreaterThanOrEqualTo(individualRunGtPercentUnique); + } + + /** + * Given a number of min/max ranges for each min/max range, call numberBetween with min/max 'n' + * times calculate the uniqueness for that given min/max range. For all 'uniqueness' values verify + * the percentage of 'uniqueness' ratios over 80% is 90%. + * + *

This isn't perfect but it ensures a pretty good degree of uniqueness in the random number + * generation. + */ + @Test + public void numberBetweenIntIntRandomizationQuality() { + Function, Double> minMaxRangeToUniquePercentageFunction = + minMax -> { + final int min = minMax.getLeft().intValue(); + final int max = minMax.getRight().intValue(); + long numbersToGet = calculateNumbersToGet(min, max); + + return uniquePercentageOfResults( + numbersToGet, () -> faker.number().numberBetween(min, max)); }; - final double percentGreaterThan80Percent = randomizationQualityTest(individualRunGtPercentUnique, minMaxRangeToUniquePercentageFunction); - assertThat(percentGreaterThan80Percent).as("Percentage of runs > 80% unique is gte 90%").isGreaterThanOrEqualTo(percentRunsGtUniquePercentage); - - // this covers Issue # 121, the number of times the function is called with the MIN/MAX values here - // is RANDOMIZATION_TESTS_MAX_NUMBERS_TO_GET - final double extremeRunUniquePercent = minMaxRangeToUniquePercentageFunction.apply(Pair.of((long) Integer.MIN_VALUE, (long) Integer.MAX_VALUE)); - assertThat(extremeRunUniquePercent).as("Percentage of extreme runs > 80%").isGreaterThanOrEqualTo(individualRunGtPercentUnique); - } - - /** - * Given a number of min/max ranges - * for each min/max range, call {@link Number#numberBetween(long, long)} with min/max 'n' times - * calculate the uniqueness for that given min/max range. - * For all 'uniqueness' values - * verify the percentage of 'uniqueness' ratios over 80% is 90%. - * - * This isn't perfect but it ensures a pretty good degree of uniqueness in the random number generation. - */ - @Test - public void numberBetweenLongLongRandomizationQuality() { - Function, Double> minMaxRangeToUniquePercentageFunction = minMax -> { - final long min = minMax.getLeft(), max = minMax.getRight(); - long numbersToGet = calculateNumbersToGet(min, max); - - return uniquePercentageOfResults(numbersToGet, () -> faker.number().numberBetween(min, max)); + final double percentGreaterThan80Percent = + randomizationQualityTest( + individualRunGtPercentUnique, minMaxRangeToUniquePercentageFunction); + assertThat(percentGreaterThan80Percent) + .as("Percentage of runs > 80% unique is gte 90%") + .isGreaterThanOrEqualTo(percentRunsGtUniquePercentage); + + // this covers Issue # 121, the number of times the function is called with the MIN/MAX values + // here + // is RANDOMIZATION_TESTS_MAX_NUMBERS_TO_GET + final double extremeRunUniquePercent = + minMaxRangeToUniquePercentageFunction.apply( + Pair.of((long) Integer.MIN_VALUE, (long) Integer.MAX_VALUE)); + assertThat(extremeRunUniquePercent) + .as("Percentage of extreme runs > 80%") + .isGreaterThanOrEqualTo(individualRunGtPercentUnique); + } + + /** + * Given a number of min/max ranges for each min/max range, call {@link Number#numberBetween(long, + * long)} with min/max 'n' times calculate the uniqueness for that given min/max range. For all + * 'uniqueness' values verify the percentage of 'uniqueness' ratios over 80% is 90%. + * + *

This isn't perfect but it ensures a pretty good degree of uniqueness in the random number + * generation. + */ + @Test + public void numberBetweenLongLongRandomizationQuality() { + Function, Double> minMaxRangeToUniquePercentageFunction = + minMax -> { + final long min = minMax.getLeft(), max = minMax.getRight(); + long numbersToGet = calculateNumbersToGet(min, max); + + return uniquePercentageOfResults( + numbersToGet, () -> faker.number().numberBetween(min, max)); }; - final double percentGreaterThan80Percent = randomizationQualityTest(individualRunGtPercentUnique, minMaxRangeToUniquePercentageFunction); - assertThat(percentGreaterThan80Percent).as("Percentage of runs > 80% unique is gte 90%").isGreaterThanOrEqualTo(percentRunsGtUniquePercentage); - - // this covers Issue # 121, the number of times the function is called with the MIN/MAX values here - // is RANDOMIZATION_TESTS_MAX_NUMBERS_TO_GET. - final double extremeRunUniquePercent = minMaxRangeToUniquePercentageFunction.apply(Pair.of(Long.MIN_VALUE, Long.MAX_VALUE)); - assertThat(extremeRunUniquePercent).as("Percentage of extreme runs > 80%").isGreaterThanOrEqualTo(individualRunGtPercentUnique); - } - - @Test - public void testRandomDoubleMaxEqualsMin() { - double actual = faker.number().randomDouble(1, 42, 42); - - double expected = BigDecimal.valueOf(42).doubleValue(); - - assertThat(actual).isEqualTo(expected); - } - - @Test - public void testDigit() { - String digit = faker.number().digit(); - - assertThat(digit).matches("[0-9]"); - } - - @Test - public void testDigits() { - String digits = faker.number().digits(5); - - assertThat(digits).matches("[0-9]{5}"); - } - - /** - * Over the series of numbers identified from RANDOMIZATION_QUALITY_RANGE_START to - * RANDOMIZATION_QUALITY_RANGE_END, create a min/max range of -value/value and - * with of those min/max values, call percentUniqueRunner. - * - * Collect the number of calls to percentUniqueRunner that were - * above the threshold and finally return that number divided by the total number of calls to - * percentUniqueRunner. - * - * @return percent of percentUniqueRunner's results greater than the threshold - */ - private double randomizationQualityTest(final double threshold, - final Function,Double> percentUniqueRunner) { - final int rangeEnd = RANDOMIZATION_QUALITY_RANGE_END; - final int rangeStep = RANDOMIZATION_QUALITY_RANGE_STEP; - final int rangeStart = RANDOMIZATION_QUALITY_RANGE_START; - - final AtomicLong greaterThanThreshold = new AtomicLong(); - final AtomicLong total = new AtomicLong(); - - for (long l = rangeStart; l < rangeEnd; l += rangeStep) { - final double percentUnique = percentUniqueRunner.apply(Pair.of(-l,l)); - logger.info("Range {} to {} is {} percent unique.", -l, l, percentUnique); - if (percentUnique > threshold) { - greaterThanThreshold.incrementAndGet(); - } - total.incrementAndGet(); - } - - return (double) greaterThanThreshold.get() / (double) total.get(); - } - - - /** - * Given a number of iterations, calls callable 'iterations' times and collects the results, - * then calculates the number of results that were unique and returns the percentage that where unique. - */ - private double uniquePercentageOfResults(long iterations, Callable callable) { - try { - List values = Lists.newArrayList(); - for (long i = 0; i < iterations; i++) { - values.add(callable.call()); - } - long setSize = Sets.newHashSet(values).size(); - return (double) setSize / (double) values.size(); - } catch (Exception e) { - logger.error("error in uniquePercentageOfResults", e); - throw new RuntimeException(e); - } + final double percentGreaterThan80Percent = + randomizationQualityTest( + individualRunGtPercentUnique, minMaxRangeToUniquePercentageFunction); + assertThat(percentGreaterThan80Percent) + .as("Percentage of runs > 80% unique is gte 90%") + .isGreaterThanOrEqualTo(percentRunsGtUniquePercentage); + + // this covers Issue # 121, the number of times the function is called with the MIN/MAX values + // here + // is RANDOMIZATION_TESTS_MAX_NUMBERS_TO_GET. + final double extremeRunUniquePercent = + minMaxRangeToUniquePercentageFunction.apply(Pair.of(Long.MIN_VALUE, Long.MAX_VALUE)); + assertThat(extremeRunUniquePercent) + .as("Percentage of extreme runs > 80%") + .isGreaterThanOrEqualTo(individualRunGtPercentUnique); + } + + @Test + public void testRandomDoubleMaxEqualsMin() { + double actual = faker.number().randomDouble(1, 42, 42); + + double expected = BigDecimal.valueOf(42).doubleValue(); + + assertThat(actual).isEqualTo(expected); + } + + @Test + public void testDigit() { + String digit = faker.number().digit(); + + assertThat(digit).matches("[0-9]"); + } + + @Test + public void testDigits() { + String digits = faker.number().digits(5); + + assertThat(digits).matches("[0-9]{5}"); + } + + /** + * Over the series of numbers identified from RANDOMIZATION_QUALITY_RANGE_START to + * RANDOMIZATION_QUALITY_RANGE_END, create a min/max range of -value/value and with of those + * min/max values, call percentUniqueRunner. + * + *

Collect the number of calls to percentUniqueRunner that were above the threshold + * and finally return that number divided by the total number of calls to + * percentUniqueRunner. + * + * @return percent of percentUniqueRunner's results greater than the threshold + */ + private double randomizationQualityTest( + final double threshold, final Function, Double> percentUniqueRunner) { + final int rangeEnd = RANDOMIZATION_QUALITY_RANGE_END; + final int rangeStep = RANDOMIZATION_QUALITY_RANGE_STEP; + final int rangeStart = RANDOMIZATION_QUALITY_RANGE_START; + + final AtomicLong greaterThanThreshold = new AtomicLong(); + final AtomicLong total = new AtomicLong(); + + for (long l = rangeStart; l < rangeEnd; l += rangeStep) { + final double percentUnique = percentUniqueRunner.apply(Pair.of(-l, l)); + logger.info("Range {} to {} is {} percent unique.", -l, l, percentUnique); + if (percentUnique > threshold) { + greaterThanThreshold.incrementAndGet(); + } + total.incrementAndGet(); } - /** - * given a range, what is the number of values to get within that range for the randomization quality tests. - */ - private long calculateNumbersToGet(long min, long max) { - long numbersToGet = Math.min((max - min) / 4, RANDOMIZATION_TESTS_MAX_NUMBERS_TO_GET); - if (numbersToGet == 0) numbersToGet = RANDOMIZATION_TESTS_MAX_NUMBERS_TO_GET; - return numbersToGet; + return (double) greaterThanThreshold.get() / (double) total.get(); + } + + /** + * Given a number of iterations, calls callable 'iterations' times and collects the + * results, then calculates the number of results that were unique and returns the percentage that + * where unique. + */ + private double uniquePercentageOfResults(long iterations, Callable callable) { + try { + List values = Lists.newArrayList(); + for (long i = 0; i < iterations; i++) { + values.add(callable.call()); + } + long setSize = Sets.newHashSet(values).size(); + return (double) setSize / (double) values.size(); + } catch (Exception e) { + logger.error("error in uniquePercentageOfResults", e); + throw new RuntimeException(e); } + } + + /** + * given a range, what is the number of values to get within that range for the randomization + * quality tests. + */ + private long calculateNumbersToGet(long min, long max) { + long numbersToGet = Math.min((max - min) / 4, RANDOMIZATION_TESTS_MAX_NUMBERS_TO_GET); + if (numbersToGet == 0) numbersToGet = RANDOMIZATION_TESTS_MAX_NUMBERS_TO_GET; + return numbersToGet; + } } diff --git a/src/test/java/org/thejavaguy/javafaker/OptionsTest.java b/src/test/java/org/thejavaguy/javafaker/OptionsTest.java index 3b74899..bc8fd08 100644 --- a/src/test/java/org/thejavaguy/javafaker/OptionsTest.java +++ b/src/test/java/org/thejavaguy/javafaker/OptionsTest.java @@ -4,58 +4,63 @@ import java.util.Arrays; import java.util.List; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class OptionsTest extends AbstractFakerTest { - private String[] options; + private String[] options; - @BeforeEach - public void setupOptions() { - options = new String[]{"A", "B", "C"}; - } + @BeforeEach + public void setupOptions() { + options = new String[] {"A", "B", "C"}; + } - @Test - public void testOptionWithArray() { - assertThat(faker.options().option(options)).isIn((Object[]) options); - } + @Test + public void testOptionWithArray() { + assertThat(faker.options().option(options)).isIn((Object[]) options); + } - @Test - public void testOptionWithVarargsString() { - assertThat(faker.options().option("A", "B", "C")).isIn((Object[]) options); - } + @Test + public void testOptionWithVarargsString() { + assertThat(faker.options().option("A", "B", "C")).isIn((Object[]) options); + } - @Test - public void testOptionWithVarargsInteger() { - Integer[] integerOptions = new Integer[] { 1, 3, 4, 5}; - assertThat(faker.options().option(1, 3, 4, 5)).isIn((Object[]) integerOptions); - } + @Test + public void testOptionWithVarargsInteger() { + Integer[] integerOptions = new Integer[] {1, 3, 4, 5}; + assertThat(faker.options().option(1, 3, 4, 5)).isIn((Object[]) integerOptions); + } - @Test - public void testOptionWithEnum() { - assertThat(faker.options().option(Day.class)).isIn((Object[]) Day.values()); - } + @Test + public void testOptionWithEnum() { + assertThat(faker.options().option(Day.class)).isIn((Object[]) Day.values()); + } - @Test - public void testNextArrayElement() { - Integer[] array = new Integer[] { 1, 2, 3, 5, 8, 13, 21 }; + @Test + public void testNextArrayElement() { + Integer[] array = new Integer[] {1, 2, 3, 5, 8, 13, 21}; - for (int i = 1; i < 10; i++) { - assertThat(faker.options().nextElement(array)).isIn(array); - } + for (int i = 1; i < 10; i++) { + assertThat(faker.options().nextElement(array)).isIn(array); } + } - @Test - public void testNextListElement() { - List list = Arrays.asList(1, 2, 3, 5, 8, 13, 21); - for (int i = 1; i < 10; i++) { - assertThat(faker.options().nextElement(list)).isIn(list); - } + @Test + public void testNextListElement() { + List list = Arrays.asList(1, 2, 3, 5, 8, 13, 21); + for (int i = 1; i < 10; i++) { + assertThat(faker.options().nextElement(list)).isIn(list); } + } - public enum Day { - MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY - } + public enum Day { + MONDAY, + TUESDAY, + WEDNESDAY, + THURSDAY, + FRIDAY, + SATURDAY, + SUNDAY + } } diff --git a/src/test/java/org/thejavaguy/javafaker/OverwatchTest.java b/src/test/java/org/thejavaguy/javafaker/OverwatchTest.java index 5e05c8a..6de1d1e 100644 --- a/src/test/java/org/thejavaguy/javafaker/OverwatchTest.java +++ b/src/test/java/org/thejavaguy/javafaker/OverwatchTest.java @@ -7,18 +7,18 @@ public class OverwatchTest extends AbstractFakerTest { - @Test - public void hero() { - assertThat(faker.overwatch().hero()).matches("^(\\w+\\.?\\s?)+$"); - } + @Test + public void hero() { + assertThat(faker.overwatch().hero()).matches("^(\\w+\\.?\\s?)+$"); + } - @Test - public void location() { - assertThat(faker.overwatch().location()).matches("^(.+'?:?\\s?)+$"); - } + @Test + public void location() { + assertThat(faker.overwatch().location()).matches("^(.+'?:?\\s?)+$"); + } - @Test - public void quote() { - assertFalse(faker.overwatch().quote().isEmpty()); - } + @Test + public void quote() { + assertFalse(faker.overwatch().quote().isEmpty()); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/PhoneNumberTest.java b/src/test/java/org/thejavaguy/javafaker/PhoneNumberTest.java index 3e3edf3..49cea62 100644 --- a/src/test/java/org/thejavaguy/javafaker/PhoneNumberTest.java +++ b/src/test/java/org/thejavaguy/javafaker/PhoneNumberTest.java @@ -3,48 +3,47 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.Locale; - import org.junit.jupiter.api.Test; public class PhoneNumberTest extends AbstractFakerTest { - @Test - public void testCellPhone_enUS() { - final Faker f = new Faker(Locale.US); - assertThat(f.phoneNumber().cellPhone()).matches("\\(?\\d+\\)?([- .]\\d+){1,3}"); - } - - @Test - public void testPhone_esMx() { - final Faker f = new Faker(new Locale("es_MX")); - for (int i=0;i<100;i++) { - assertThat(f.phoneNumber().cellPhone()).matches("(044 )?\\(?\\d+\\)?([- .]\\d+){1,3}"); - assertThat(f.phoneNumber().phoneNumber()).matches("\\(?\\d+\\)?([- .]\\d+){1,3}"); - } - } - - @Test - public void testCellPhone() { - assertThat(faker.phoneNumber().cellPhone()).matches("\\(?\\d+\\)?([- .]\\d+){1,3}"); - } - - @Test - public void testPhoneNumber() { - assertThat(faker.phoneNumber().phoneNumber()).matches("\\(?\\d+\\)?([- .]x?\\d+){1,5}"); - } - - @Test - public void testExtension() { - assertThat(faker.phoneNumber().extension()).matches("\\d{4}"); - } - - @Test - public void testSubscriberNumber() { - assertThat(faker.phoneNumber().subscriberNumber()).matches("\\d{4}"); - } - - @Test - public void testSubscriberNumberWithLength() { - assertThat(faker.phoneNumber().subscriberNumber(10)).matches("\\d{10}"); + @Test + public void testCellPhone_enUS() { + final Faker f = new Faker(Locale.US); + assertThat(f.phoneNumber().cellPhone()).matches("\\(?\\d+\\)?([- .]\\d+){1,3}"); + } + + @Test + public void testPhone_esMx() { + final Faker f = new Faker(new Locale("es_MX")); + for (int i = 0; i < 100; i++) { + assertThat(f.phoneNumber().cellPhone()).matches("(044 )?\\(?\\d+\\)?([- .]\\d+){1,3}"); + assertThat(f.phoneNumber().phoneNumber()).matches("\\(?\\d+\\)?([- .]\\d+){1,3}"); } + } + + @Test + public void testCellPhone() { + assertThat(faker.phoneNumber().cellPhone()).matches("\\(?\\d+\\)?([- .]\\d+){1,3}"); + } + + @Test + public void testPhoneNumber() { + assertThat(faker.phoneNumber().phoneNumber()).matches("\\(?\\d+\\)?([- .]x?\\d+){1,5}"); + } + + @Test + public void testExtension() { + assertThat(faker.phoneNumber().extension()).matches("\\d{4}"); + } + + @Test + public void testSubscriberNumber() { + assertThat(faker.phoneNumber().subscriberNumber()).matches("\\d{4}"); + } + + @Test + public void testSubscriberNumberWithLength() { + assertThat(faker.phoneNumber().subscriberNumber(10)).matches("\\d{10}"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/PhotographyTest.java b/src/test/java/org/thejavaguy/javafaker/PhotographyTest.java index 3c67792..c0ae5e5 100644 --- a/src/test/java/org/thejavaguy/javafaker/PhotographyTest.java +++ b/src/test/java/org/thejavaguy/javafaker/PhotographyTest.java @@ -9,66 +9,66 @@ import org.junit.jupiter.api.TestTemplate; import org.thejavaguy.javafaker.repeating.Repeat; -public class PhotographyTest extends AbstractFakerTest{ +public class PhotographyTest extends AbstractFakerTest { - @Test - public void testAperture() { - final String value = faker.photography().aperture(); - assertTrue(value.startsWith("f")); - } + @Test + public void testAperture() { + final String value = faker.photography().aperture(); + assertTrue(value.startsWith("f")); + } - @Test - public void testTerm() { - final String value = faker.photography().term(); - assertNonNullOrEmpty(value); - } + @Test + public void testTerm() { + final String value = faker.photography().term(); + assertNonNullOrEmpty(value); + } - @Test - public void brand() { - final String value = faker.photography().brand(); - assertNonNullOrEmpty(value); - } + @Test + public void brand() { + final String value = faker.photography().brand(); + assertNonNullOrEmpty(value); + } - @Test - public void camera() { - final String value = faker.photography().camera(); - assertNonNullOrEmpty(value); - } + @Test + public void camera() { + final String value = faker.photography().camera(); + assertNonNullOrEmpty(value); + } - @Test - public void lens() { - final String value = faker.photography().lens(); - assertNonNullOrEmpty(value); - } + @Test + public void lens() { + final String value = faker.photography().lens(); + assertNonNullOrEmpty(value); + } - @Test - public void genre() { - final String value = faker.photography().genre(); - assertNonNullOrEmpty(value); - } + @Test + public void genre() { + final String value = faker.photography().genre(); + assertNonNullOrEmpty(value); + } - @Test - public void imageTag() { - final String value = faker.photography().imageTag(); - assertNonNullOrEmpty(value); - } + @Test + public void imageTag() { + final String value = faker.photography().imageTag(); + assertNonNullOrEmpty(value); + } - @TestTemplate - @Repeat(times=7) - public void shutter() { - final String value = faker.photography().shutter(); - assertThat(value).matches("\\d{1,}\\/{0,1}\\d*"); - } + @TestTemplate + @Repeat(times = 7) + public void shutter() { + final String value = faker.photography().shutter(); + assertThat(value).matches("\\d{1,}\\/{0,1}\\d*"); + } - @TestTemplate - @Repeat(times=7) - public void iso() { - final String value = faker.photography().iso(); - assertThat(value).matches("\\d{1,}"); - } + @TestTemplate + @Repeat(times = 7) + public void iso() { + final String value = faker.photography().iso(); + assertThat(value).matches("\\d{1,}"); + } - private static void assertNonNullOrEmpty(String value) { - assertNotNull(value); - assertFalse(value.isEmpty()); - } + private static void assertNonNullOrEmpty(String value) { + assertNotNull(value); + assertFalse(value.isEmpty()); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/PokemonTest.java b/src/test/java/org/thejavaguy/javafaker/PokemonTest.java index 872f74e..1811187 100644 --- a/src/test/java/org/thejavaguy/javafaker/PokemonTest.java +++ b/src/test/java/org/thejavaguy/javafaker/PokemonTest.java @@ -6,13 +6,13 @@ public class PokemonTest extends AbstractFakerTest { - @Test - public void name() { - assertThat(faker.pokemon().name()).matches("[\\w']+.?( \\w+)?"); - } + @Test + public void name() { + assertThat(faker.pokemon().name()).matches("[\\w']+.?( \\w+)?"); + } - @Test - public void location() { - assertThat(faker.pokemon().location()).matches("\\w+( \\w+)?( \\w+)?"); - } + @Test + public void location() { + assertThat(faker.pokemon().location()).matches("\\w+( \\w+)?( \\w+)?"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/PrincessBrideTest.java b/src/test/java/org/thejavaguy/javafaker/PrincessBrideTest.java index 68664b2..dda88b7 100644 --- a/src/test/java/org/thejavaguy/javafaker/PrincessBrideTest.java +++ b/src/test/java/org/thejavaguy/javafaker/PrincessBrideTest.java @@ -5,13 +5,13 @@ import org.junit.jupiter.api.Test; public class PrincessBrideTest extends AbstractFakerTest { - @Test - public void character() { - assertThat(faker.princessBride().character()).matches("[A-Za-z .-]+"); - } + @Test + public void character() { + assertThat(faker.princessBride().character()).matches("[A-Za-z .-]+"); + } - @Test - public void quote() { - assertThat(faker.princessBride().quote()).isNotEmpty(); - } + @Test + public void quote() { + assertThat(faker.princessBride().quote()).isNotEmpty(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/ProgrammingLanguageTest.java b/src/test/java/org/thejavaguy/javafaker/ProgrammingLanguageTest.java index a6600fc..685c84d 100644 --- a/src/test/java/org/thejavaguy/javafaker/ProgrammingLanguageTest.java +++ b/src/test/java/org/thejavaguy/javafaker/ProgrammingLanguageTest.java @@ -6,14 +6,13 @@ public class ProgrammingLanguageTest extends AbstractFakerTest { - @Test - public void name() { - assertThat(faker.programmingLanguage().name()).matches("[A-Za-z0-9 :,.+*()#/\\–\\-@πéöü'′!]+"); - } - - @Test - public void creator() { - assertThat(faker.programmingLanguage().creator()).matches("[A-Za-z .,\\-]+"); - } + @Test + public void name() { + assertThat(faker.programmingLanguage().name()).matches("[A-Za-z0-9 :,.+*()#/\\–\\-@πéöü'′!]+"); + } + @Test + public void creator() { + assertThat(faker.programmingLanguage().creator()).matches("[A-Za-z .,\\-]+"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/RandomFakerTest.java b/src/test/java/org/thejavaguy/javafaker/RandomFakerTest.java index a97716f..0fa7cbe 100644 --- a/src/test/java/org/thejavaguy/javafaker/RandomFakerTest.java +++ b/src/test/java/org/thejavaguy/javafaker/RandomFakerTest.java @@ -3,64 +3,63 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.Random; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class RandomFakerTest extends AbstractFakerTest { - private static final int CONSTANT_SEED_VALUE = 10; - private Faker faker; - private Random random; + private static final int CONSTANT_SEED_VALUE = 10; + private Faker faker; + private Random random; - @BeforeEach - public void before() { - super.before(); - random = new Random(); - faker = new Faker(random); - } + @BeforeEach + public void before() { + super.before(); + random = new Random(); + faker = new Faker(random); + } - @Test - public void testNumerifyRandomnessCanBeControlled() { - resetRandomSeed(); - final String firstInvocation = faker.numerify("###"); + @Test + public void testNumerifyRandomnessCanBeControlled() { + resetRandomSeed(); + final String firstInvocation = faker.numerify("###"); - resetRandomSeed(); - final String secondInvocation = faker.numerify("###"); - assertThat(firstInvocation).isEqualTo(secondInvocation); - } + resetRandomSeed(); + final String secondInvocation = faker.numerify("###"); + assertThat(firstInvocation).isEqualTo(secondInvocation); + } - @Test - public void testLetterifyRandomnessCanBeControlled() { - resetRandomSeed(); - final String firstInvocation = faker.letterify("???"); + @Test + public void testLetterifyRandomnessCanBeControlled() { + resetRandomSeed(); + final String firstInvocation = faker.letterify("???"); - resetRandomSeed(); - final String secondInvocation = faker.letterify("???"); - assertThat(firstInvocation).isEqualTo(secondInvocation); - } + resetRandomSeed(); + final String secondInvocation = faker.letterify("???"); + assertThat(firstInvocation).isEqualTo(secondInvocation); + } - @Test - public void testNameRandomnessCanBeControlled() { - resetRandomSeed(); - final String firstInvocation = faker.name().name(); + @Test + public void testNameRandomnessCanBeControlled() { + resetRandomSeed(); + final String firstInvocation = faker.name().name(); - resetRandomSeed(); - final String secondInvocation = faker.name().name(); - assertThat(firstInvocation).isEqualTo(secondInvocation); - } + resetRandomSeed(); + final String secondInvocation = faker.name().name(); + assertThat(firstInvocation).isEqualTo(secondInvocation); + } - @Test - public void testEmailRandomnessCanBeControlled() { - resetRandomSeed(); - final String firstInvocation = faker.internet().emailAddress(); + @Test + public void testEmailRandomnessCanBeControlled() { + resetRandomSeed(); + final String firstInvocation = faker.internet().emailAddress(); - resetRandomSeed(); - final String secondInvocation = faker.internet().emailAddress(); - assertThat(firstInvocation).isEqualTo(secondInvocation); - } + resetRandomSeed(); + final String secondInvocation = faker.internet().emailAddress(); + assertThat(firstInvocation).isEqualTo(secondInvocation); + } - private void resetRandomSeed() { - random.setSeed(CONSTANT_SEED_VALUE); - } + private void resetRandomSeed() { + random.setSeed(CONSTANT_SEED_VALUE); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/RelationshipTest.java b/src/test/java/org/thejavaguy/javafaker/RelationshipTest.java index 6fe459f..f0c5af2 100644 --- a/src/test/java/org/thejavaguy/javafaker/RelationshipTest.java +++ b/src/test/java/org/thejavaguy/javafaker/RelationshipTest.java @@ -5,86 +5,92 @@ import static org.mockito.Mockito.when; import java.lang.reflect.InvocationTargetException; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; public class RelationshipTest extends AbstractFakerTest { - private Faker mockFaker; - - @BeforeEach - public void before() { - super.before(); - mockFaker = Mockito.mock(Faker.class); - } - - @Test - public void anyTest() { - assertThat(faker.relationships().any()).isNotEmpty(); - } - - @Test - public void directTest() { - assertThat(faker.relationships().direct()).isNotEmpty(); - } - - @Test - public void extendedTest() { - assertThat(faker.relationships().extended()).isNotEmpty(); - } - - @Test - public void inLawTest() { - assertThat(faker.relationships().inLaw()).isNotEmpty(); - } - - @Test - public void spouseTest() { - assertThat(faker.relationships().spouse()).isNotEmpty(); - } - - @Test - public void parentTest() { - assertThat(faker.relationships().parent()).isNotEmpty(); - } - - @Test - public void siblingTest() { - assertThat(faker.relationships().sibling()).isNotEmpty(); - } - - @Test - public void anyWithIllegalArgumentExceptionThrown() { - assertThrows(RuntimeException.class, () -> { - when(mockFaker.random()).thenThrow(new IllegalArgumentException()); - new Relationships(mockFaker).any(); + private Faker mockFaker; + + @BeforeEach + public void before() { + super.before(); + mockFaker = Mockito.mock(Faker.class); + } + + @Test + public void anyTest() { + assertThat(faker.relationships().any()).isNotEmpty(); + } + + @Test + public void directTest() { + assertThat(faker.relationships().direct()).isNotEmpty(); + } + + @Test + public void extendedTest() { + assertThat(faker.relationships().extended()).isNotEmpty(); + } + + @Test + public void inLawTest() { + assertThat(faker.relationships().inLaw()).isNotEmpty(); + } + + @Test + public void spouseTest() { + assertThat(faker.relationships().spouse()).isNotEmpty(); + } + + @Test + public void parentTest() { + assertThat(faker.relationships().parent()).isNotEmpty(); + } + + @Test + public void siblingTest() { + assertThat(faker.relationships().sibling()).isNotEmpty(); + } + + @Test + public void anyWithIllegalArgumentExceptionThrown() { + assertThrows( + RuntimeException.class, + () -> { + when(mockFaker.random()).thenThrow(new IllegalArgumentException()); + new Relationships(mockFaker).any(); }); - } - - @Test - public void anyWithSecurityExceptionThrown() { - assertThrows(RuntimeException.class, () -> { - when(mockFaker.random()).thenThrow(new SecurityException()); - new Relationships(mockFaker).any(); + } + + @Test + public void anyWithSecurityExceptionThrown() { + assertThrows( + RuntimeException.class, + () -> { + when(mockFaker.random()).thenThrow(new SecurityException()); + new Relationships(mockFaker).any(); }); - } - - @Test - public void anyWithIllegalAccessExceptionThrown() { - assertThrows(RuntimeException.class, () -> { - when(mockFaker.random()).thenThrow(new IllegalAccessException()); - new Relationships(mockFaker).any(); + } + + @Test + public void anyWithIllegalAccessExceptionThrown() { + assertThrows( + RuntimeException.class, + () -> { + when(mockFaker.random()).thenThrow(new IllegalAccessException()); + new Relationships(mockFaker).any(); }); - } - - @Test - public void anyWithInvocationTargetExceptionThrown() { - assertThrows(RuntimeException.class, () -> { - when(mockFaker.random()).thenThrow(new InvocationTargetException(new Exception())); - new Relationships(mockFaker).any(); + } + + @Test + public void anyWithInvocationTargetExceptionThrown() { + assertThrows( + RuntimeException.class, + () -> { + when(mockFaker.random()).thenThrow(new InvocationTargetException(new Exception())); + new Relationships(mockFaker).any(); }); - } - + } } diff --git a/src/test/java/org/thejavaguy/javafaker/RickAndMortyTest.java b/src/test/java/org/thejavaguy/javafaker/RickAndMortyTest.java index 5b910d5..1ec5970 100644 --- a/src/test/java/org/thejavaguy/javafaker/RickAndMortyTest.java +++ b/src/test/java/org/thejavaguy/javafaker/RickAndMortyTest.java @@ -6,18 +6,18 @@ public class RickAndMortyTest extends AbstractFakerTest { - @Test - public void character() { - assertThat(faker.rickAndMorty().character()).matches("^([\\w'-.]+ ?){2,}$"); - } + @Test + public void character() { + assertThat(faker.rickAndMorty().character()).matches("^([\\w'-.]+ ?){2,}$"); + } - @Test - public void location() { - assertThat(faker.rickAndMorty().location()).matches("^([\\w-.]+ ?){2,}$"); - } + @Test + public void location() { + assertThat(faker.rickAndMorty().location()).matches("^([\\w-.]+ ?){2,}$"); + } - @Test - public void quote() { - assertThat(faker.rickAndMorty().quote()).isNotEmpty(); - } + @Test + public void quote() { + assertThat(faker.rickAndMorty().quote()).isNotEmpty(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/RobinTest.java b/src/test/java/org/thejavaguy/javafaker/RobinTest.java index 9432f98..a146eec 100644 --- a/src/test/java/org/thejavaguy/javafaker/RobinTest.java +++ b/src/test/java/org/thejavaguy/javafaker/RobinTest.java @@ -6,8 +6,8 @@ public class RobinTest extends AbstractFakerTest { - @Test - public void quote() { - assertThat(faker.robin().quote()).matches("^(\\w+\\.?-?'?\\s?)+(\\(?)?(\\w+\\s?\\.?)+(\\))?$"); - } + @Test + public void quote() { + assertThat(faker.robin().quote()).matches("^(\\w+\\.?-?'?\\s?)+(\\(?)?(\\w+\\s?\\.?)+(\\))?$"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/RockBandTest.java b/src/test/java/org/thejavaguy/javafaker/RockBandTest.java index 425a811..8a6f45b 100644 --- a/src/test/java/org/thejavaguy/javafaker/RockBandTest.java +++ b/src/test/java/org/thejavaguy/javafaker/RockBandTest.java @@ -6,8 +6,8 @@ public class RockBandTest extends AbstractFakerTest { - @Test - public void name() { - assertThat(faker.rockBand().name()).matches("([\\w'/.,&]+ ?)+"); - } + @Test + public void name() { + assertThat(faker.rockBand().name()).matches("([\\w'/.,&]+ ?)+"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/ShakespeareTest.java b/src/test/java/org/thejavaguy/javafaker/ShakespeareTest.java index d91cc7e..aadc24f 100644 --- a/src/test/java/org/thejavaguy/javafaker/ShakespeareTest.java +++ b/src/test/java/org/thejavaguy/javafaker/ShakespeareTest.java @@ -4,26 +4,25 @@ import org.junit.jupiter.api.Test; -public class ShakespeareTest extends AbstractFakerTest{ - - @Test - public void testHamletQuote() { - assertThat(faker.shakespeare().hamletQuote()).isNotEmpty(); - } - - @Test - public void testAsYouLikeItQuote() { - assertThat(faker.shakespeare().asYouLikeItQuote()).isNotEmpty(); - } - - @Test - public void testKingRichardIIIQuote() { - assertThat(faker.shakespeare().kingRichardIIIQuote()).isNotEmpty(); - } - - @Test - public void testRomeoAndJulietQuote() { - assertThat(faker.shakespeare().romeoAndJulietQuote()).isNotEmpty(); - } - +public class ShakespeareTest extends AbstractFakerTest { + + @Test + public void testHamletQuote() { + assertThat(faker.shakespeare().hamletQuote()).isNotEmpty(); + } + + @Test + public void testAsYouLikeItQuote() { + assertThat(faker.shakespeare().asYouLikeItQuote()).isNotEmpty(); + } + + @Test + public void testKingRichardIIIQuote() { + assertThat(faker.shakespeare().kingRichardIIIQuote()).isNotEmpty(); + } + + @Test + public void testRomeoAndJulietQuote() { + assertThat(faker.shakespeare().romeoAndJulietQuote()).isNotEmpty(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/ShippingTest.java b/src/test/java/org/thejavaguy/javafaker/ShippingTest.java index fb8ad32..9e8be50 100644 --- a/src/test/java/org/thejavaguy/javafaker/ShippingTest.java +++ b/src/test/java/org/thejavaguy/javafaker/ShippingTest.java @@ -5,213 +5,223 @@ import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; - import org.junit.jupiter.api.Test; public class ShippingTest extends AbstractFakerTest { - @Test - void carrier() { - assertThat(faker.shipping().carrier()).isNotBlank(); - } - - @Test - void shippingMethod() { - assertThat(faker.shipping().shippingMethod()).isNotBlank(); - } - - @Test - void status() { - String status = faker.shipping().status(); - assertThat(status).isNotBlank(); - assertThat(status).isIn("pending", "label_created", "picked_up", "in_transit", - "out_for_delivery", "delivered", "attempted_delivery", "exception", - "returned", "on_hold", "customs_clearance", "at_local_facility"); - } - - @Test - void packageType() { - assertThat(faker.shipping().packageType()).isNotBlank(); - } - - @Test - void handlingInstruction() { - assertThat(faker.shipping().handlingInstruction()).isNotBlank(); - } - - @Test - void exceptionType() { - assertThat(faker.shipping().exceptionType()).isNotBlank(); - } - - @Test - void trackingNumberUps() { - String tracking = faker.shipping().trackingNumberUps(); - assertThat(tracking).startsWith("1Z"); - assertThat(tracking).hasSize(18); - } - - @Test - void trackingNumberFedEx() { - String tracking = faker.shipping().trackingNumberFedEx(); - assertThat(tracking).matches("\\d{4}-\\d{4}-\\d{4}"); - } - - @Test - void trackingNumberUsps() { - String tracking = faker.shipping().trackingNumberUsps(); - assertThat(tracking).matches("\\d{22}"); - } - - @Test - void trackingNumberDhl() { - String tracking = faker.shipping().trackingNumberDhl(); - assertThat(tracking).matches("\\d{10}"); - } - - @Test - void trackingNumber() { - // Just verify it generates something - assertThat(faker.shipping().trackingNumber()).isNotBlank(); - } - - @Test - void shipmentId() { - String id = faker.shipping().shipmentId(); - assertThat(id).startsWith("SHP-"); - assertThat(id).matches("SHP-\\d{8}-[A-Z]{3}\\d{3}"); - } - - @Test - void weight() { - BigDecimal weight = faker.shipping().weight(); - assertThat(weight).isGreaterThanOrEqualTo(BigDecimal.valueOf(0.1)); - assertThat(weight).isLessThanOrEqualTo(BigDecimal.valueOf(50.0)); - } - - @Test - void weightWithRange() { - BigDecimal weight = faker.shipping().weight(1.0, 5.0); - assertThat(weight).isGreaterThanOrEqualTo(BigDecimal.valueOf(1.0)); - assertThat(weight).isLessThanOrEqualTo(BigDecimal.valueOf(5.0)); - } - - @Test - void weightFormatted() { - String weight = faker.shipping().weightFormatted(); - assertThat(weight).matches("\\d+\\.\\d+ (lb|oz|kg|g)"); - } - - @Test - void dimensions() { - String dims = faker.shipping().dimensions(); - assertThat(dims).matches("\\d+ x \\d+ x \\d+ (in|cm|mm)"); - } - - @Test - void dimensionValues() { - int[] dims = faker.shipping().dimensionValues(); - assertThat(dims).hasSize(3); - assertThat(dims[0]).isGreaterThan(0); // length - assertThat(dims[1]).isGreaterThan(0); // width - assertThat(dims[2]).isGreaterThan(0); // height - } - - @Test - void shippingCost() { - BigDecimal cost = faker.shipping().shippingCost(); - assertThat(cost).isGreaterThanOrEqualTo(BigDecimal.valueOf(5.99)); - assertThat(cost).isLessThanOrEqualTo(BigDecimal.valueOf(99.99)); - assertThat(cost.scale()).isEqualTo(2); - } - - @Test - void shippingCostFormatted() { - String cost = faker.shipping().shippingCostFormatted(); - assertThat(cost).matches("\\$\\d+\\.\\d{2}"); - } - - @Test - void estimatedDeliveryDate() { - LocalDate date = faker.shipping().estimatedDeliveryDate(); - assertThat(date).isAfter(LocalDate.now().plusDays(2)); - assertThat(date).isBeforeOrEqualTo(LocalDate.now().plusDays(14)); - } - - @Test - void shipDate() { - LocalDate date = faker.shipping().shipDate(); - assertThat(date).isBeforeOrEqualTo(LocalDate.now()); - assertThat(date).isAfterOrEqualTo(LocalDate.now().minusDays(7)); - } - - @Test - void deliveryDateTime() { - LocalDateTime dt = faker.shipping().deliveryDateTime(); - assertThat(dt).isNotNull(); - assertThat(dt.getHour()).isBetween(8, 19); - } - - @Test - void deliveryWindow() { - String window = faker.shipping().deliveryWindow(); - assertThat(window).matches("\\d{1,2}:\\d{2} [AP]M - \\d{1,2}:\\d{2} [AP]M"); - } - - @Test - void insuredValue() { - BigDecimal value = faker.shipping().insuredValue(); - assertThat(value).isGreaterThanOrEqualTo(BigDecimal.ZERO); - assertThat(value.scale()).isEqualTo(2); - } - - @Test - void codAmount() { - BigDecimal amount = faker.shipping().codAmount(); - assertThat(amount).isGreaterThanOrEqualTo(BigDecimal.valueOf(10.00)); - assertThat(amount.scale()).isEqualTo(2); - } - - @Test - void referenceNumber() { - String ref = faker.shipping().referenceNumber(); - assertThat(ref).matches("(PO-|REF-|ORD-|INV-)?\\d{8}"); - } - - @Test - void facilityLocation() { - String location = faker.shipping().facilityLocation(); - assertThat(location).isNotBlank(); - assertThat(location).contains(","); // City, State - } - - @Test - void barcode() { - String barcode = faker.shipping().barcode(); - assertThat(barcode).matches("\\d{20}"); - } - - @Test - void zone() { - int zone = faker.shipping().zone(); - assertThat(zone).isBetween(1, 8); - } - - @Test - void signatureRequired() { - boolean sig = faker.shipping().signatureRequired(); - assertThat(sig).isIn(true, false); - } - - @Test - void hazardousMaterials() { - boolean hazmat = faker.shipping().hazardousMaterials(); - assertThat(hazmat).isIn(true, false); - } - - @Test - void trackingEvent() { - String event = faker.shipping().trackingEvent(); - assertThat(event).isNotBlank(); - } + @Test + void carrier() { + assertThat(faker.shipping().carrier()).isNotBlank(); + } + + @Test + void shippingMethod() { + assertThat(faker.shipping().shippingMethod()).isNotBlank(); + } + + @Test + void status() { + String status = faker.shipping().status(); + assertThat(status).isNotBlank(); + assertThat(status) + .isIn( + "pending", + "label_created", + "picked_up", + "in_transit", + "out_for_delivery", + "delivered", + "attempted_delivery", + "exception", + "returned", + "on_hold", + "customs_clearance", + "at_local_facility"); + } + + @Test + void packageType() { + assertThat(faker.shipping().packageType()).isNotBlank(); + } + + @Test + void handlingInstruction() { + assertThat(faker.shipping().handlingInstruction()).isNotBlank(); + } + + @Test + void exceptionType() { + assertThat(faker.shipping().exceptionType()).isNotBlank(); + } + + @Test + void trackingNumberUps() { + String tracking = faker.shipping().trackingNumberUps(); + assertThat(tracking).startsWith("1Z"); + assertThat(tracking).hasSize(18); + } + + @Test + void trackingNumberFedEx() { + String tracking = faker.shipping().trackingNumberFedEx(); + assertThat(tracking).matches("\\d{4}-\\d{4}-\\d{4}"); + } + + @Test + void trackingNumberUsps() { + String tracking = faker.shipping().trackingNumberUsps(); + assertThat(tracking).matches("\\d{22}"); + } + + @Test + void trackingNumberDhl() { + String tracking = faker.shipping().trackingNumberDhl(); + assertThat(tracking).matches("\\d{10}"); + } + + @Test + void trackingNumber() { + // Just verify it generates something + assertThat(faker.shipping().trackingNumber()).isNotBlank(); + } + + @Test + void shipmentId() { + String id = faker.shipping().shipmentId(); + assertThat(id).startsWith("SHP-"); + assertThat(id).matches("SHP-\\d{8}-[A-Z]{3}\\d{3}"); + } + + @Test + void weight() { + BigDecimal weight = faker.shipping().weight(); + assertThat(weight).isGreaterThanOrEqualTo(BigDecimal.valueOf(0.1)); + assertThat(weight).isLessThanOrEqualTo(BigDecimal.valueOf(50.0)); + } + + @Test + void weightWithRange() { + BigDecimal weight = faker.shipping().weight(1.0, 5.0); + assertThat(weight).isGreaterThanOrEqualTo(BigDecimal.valueOf(1.0)); + assertThat(weight).isLessThanOrEqualTo(BigDecimal.valueOf(5.0)); + } + + @Test + void weightFormatted() { + String weight = faker.shipping().weightFormatted(); + assertThat(weight).matches("\\d+\\.\\d+ (lb|oz|kg|g)"); + } + + @Test + void dimensions() { + String dims = faker.shipping().dimensions(); + assertThat(dims).matches("\\d+ x \\d+ x \\d+ (in|cm|mm)"); + } + + @Test + void dimensionValues() { + int[] dims = faker.shipping().dimensionValues(); + assertThat(dims).hasSize(3); + assertThat(dims[0]).isGreaterThan(0); // length + assertThat(dims[1]).isGreaterThan(0); // width + assertThat(dims[2]).isGreaterThan(0); // height + } + + @Test + void shippingCost() { + BigDecimal cost = faker.shipping().shippingCost(); + assertThat(cost).isGreaterThanOrEqualTo(BigDecimal.valueOf(5.99)); + assertThat(cost).isLessThanOrEqualTo(BigDecimal.valueOf(99.99)); + assertThat(cost.scale()).isEqualTo(2); + } + + @Test + void shippingCostFormatted() { + String cost = faker.shipping().shippingCostFormatted(); + assertThat(cost).matches("\\$\\d+\\.\\d{2}"); + } + + @Test + void estimatedDeliveryDate() { + LocalDate date = faker.shipping().estimatedDeliveryDate(); + assertThat(date).isAfter(LocalDate.now().plusDays(2)); + assertThat(date).isBeforeOrEqualTo(LocalDate.now().plusDays(14)); + } + + @Test + void shipDate() { + LocalDate date = faker.shipping().shipDate(); + assertThat(date).isBeforeOrEqualTo(LocalDate.now()); + assertThat(date).isAfterOrEqualTo(LocalDate.now().minusDays(7)); + } + + @Test + void deliveryDateTime() { + LocalDateTime dt = faker.shipping().deliveryDateTime(); + assertThat(dt).isNotNull(); + assertThat(dt.getHour()).isBetween(8, 19); + } + + @Test + void deliveryWindow() { + String window = faker.shipping().deliveryWindow(); + assertThat(window).matches("\\d{1,2}:\\d{2} [AP]M - \\d{1,2}:\\d{2} [AP]M"); + } + + @Test + void insuredValue() { + BigDecimal value = faker.shipping().insuredValue(); + assertThat(value).isGreaterThanOrEqualTo(BigDecimal.ZERO); + assertThat(value.scale()).isEqualTo(2); + } + + @Test + void codAmount() { + BigDecimal amount = faker.shipping().codAmount(); + assertThat(amount).isGreaterThanOrEqualTo(BigDecimal.valueOf(10.00)); + assertThat(amount.scale()).isEqualTo(2); + } + + @Test + void referenceNumber() { + String ref = faker.shipping().referenceNumber(); + assertThat(ref).matches("(PO-|REF-|ORD-|INV-)?\\d{8}"); + } + + @Test + void facilityLocation() { + String location = faker.shipping().facilityLocation(); + assertThat(location).isNotBlank(); + assertThat(location).contains(","); // City, State + } + + @Test + void barcode() { + String barcode = faker.shipping().barcode(); + assertThat(barcode).matches("\\d{20}"); + } + + @Test + void zone() { + int zone = faker.shipping().zone(); + assertThat(zone).isBetween(1, 8); + } + + @Test + void signatureRequired() { + boolean sig = faker.shipping().signatureRequired(); + assertThat(sig).isIn(true, false); + } + + @Test + void hazardousMaterials() { + boolean hazmat = faker.shipping().hazardousMaterials(); + assertThat(hazmat).isIn(true, false); + } + + @Test + void trackingEvent() { + String event = faker.shipping().trackingEvent(); + assertThat(event).isNotBlank(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/SipTest.java b/src/test/java/org/thejavaguy/javafaker/SipTest.java index 3038af4..acc906c 100644 --- a/src/test/java/org/thejavaguy/javafaker/SipTest.java +++ b/src/test/java/org/thejavaguy/javafaker/SipTest.java @@ -6,143 +6,130 @@ public class SipTest extends AbstractFakerTest { - @Test - public void method_returnUpperCaseWithMinimum3Chars() { - assertThat(faker.sip().method()).matches("^[A-Z]{3,}$"); - } - - @Test - public void contentType_returnLowerCaseTwoWordsSepereatedBySlashMinimum3And4Chars() { - assertThat(faker.sip().contentType()).matches("^[a-z]{4,}[/]{1,}[a-z0-9-]{3,}$"); - } - - @Test - public void messagingPort_return4DigitIntBetween1000And9999() { - assertThat(faker.sip().messagingPort()) - .isGreaterThanOrEqualTo(1000) - .isLessThan(10000); - } - - @Test - public void rtpPort_returnPositiveEvenInt() { - int sut = faker.sip().rtpPort(); - assertThat(sut).isGreaterThanOrEqualTo(2); - assertThat(sut % 2).isEqualTo(0); - } - - @Test - public void provisionalResponseCode_return3DigitIntBetween100And199() { - assertThat(faker.sip().provisionalResponseCode()) - .isGreaterThanOrEqualTo(100) - .isLessThan(200); - } - - @Test - public void successResponse_Codereturn3DigitIntBetween200And299() { - assertThat(faker.sip().successResponseCode()) - .isGreaterThanOrEqualTo(200) - .isLessThan(300); - } - - @Test - public void redirectResponseCode_Codereturn3DigitIntBetween300And399() { - assertThat(faker.sip().redirectResponseCode()) - .isGreaterThanOrEqualTo(300) - .isLessThan(400); - } - - @Test - public void clientErrorResponseCode_Codereturn3DigitIntBetween400And499() { - assertThat(faker.sip().clientErrorResponseCode()) - .isGreaterThanOrEqualTo(400) - .isLessThan(500); - } - - @Test - public void serverErrorResponseCode_Codereturn3DigitIntBetween500And599() { - assertThat(faker.sip().serverErrorResponseCode()) - .isGreaterThanOrEqualTo(500) - .isLessThan(600); - } - - @Test - public void globalErrorResponseCode_Codereturn3DigitIntBetween600And699() { - assertThat(faker.sip().globalErrorResponseCode()) - .isGreaterThanOrEqualTo(600) - .isLessThan(700); - } - - @Test - public void provisionalResponsePhrase_returnAnyNonDigitString() { - assertThat(faker.sip().provisionalResponsePhrase()).matches("\\D+"); - } - - @Test - public void successResponsePhrase_returnAnyNonDigitString() { - assertThat(faker.sip().successResponsePhrase()).matches("\\D+"); - } - - @Test - public void redirectResponsePhrase_returnAnyNonDigitString() { - assertThat(faker.sip().redirectResponsePhrase()).matches("\\D+"); - } - - @Test - public void clientErrorResponsePhrase_returnAnyNonDigitString() { - assertThat(faker.sip().clientErrorResponsePhrase()).matches("\\D+"); - } - - @Test - public void serverErrorResponsePhrase_returnAnyNonDigitString() { - assertThat(faker.sip().serverErrorResponsePhrase()).matches("\\D+"); - } - - @Test - public void globalErrorResponsePhrase_returnAnyNonDigitString() { - assertThat(faker.sip().globalErrorResponsePhrase()).matches("\\D+"); - } - - @Test - public void bodyString_returnAValidSdpBodyString() { - String[] sut = faker.sip().bodyString().split("\n"); - - assertThat(sut.length).isEqualTo(7); - - assertThat(sut[0]).isEqualTo("v=0"); - - String[] secondLine = sut[1].split(" "); - assertThat(secondLine[0]).startsWith("o="); - assertThat(secondLine[1]).matches("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"); - assertThat(secondLine[secondLine.length - 1]).matches("[a-z]+\\.\\w{2,4}"); - - assertThat(sut[2]).isEqualTo("s=-"); - - String[] fourthLine = sut[3].split(" "); - assertThat(fourthLine[0]).isEqualTo("c=IN"); - assertThat(fourthLine[fourthLine.length - 1]).matches("^\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}$"); - - assertThat(sut[4]).isEqualTo("t=0 0"); - - String[] sixthLine = sut[5].split(" "); - assertThat(sixthLine[0]).isEqualTo("m=audio"); - assertThat(Integer.parseInt(sixthLine[1])).isGreaterThanOrEqualTo(2); - assertThat(Integer.parseInt(sixthLine[1]) % 2).isEqualTo(0); - - assertThat(sut[6]).isEqualTo("a=rtpmap:0 PCMU/8000"); - } - - @Test - public void bodyBytes_isNotNull() { - byte[] sut = faker.sip().bodyBytes(); - - assertThat(sut.length).isNotNull(); - } - - @Test - public void nameAddress_returnValidNameAddressString() { - String[] sut = faker.sip().nameAddress().split("@"); - - assertThat(sut[0].split(":")[1]).matches("\\w+"); - assertThat(sut[1].split(":")[0]).matches("^\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}$"); - } + @Test + public void method_returnUpperCaseWithMinimum3Chars() { + assertThat(faker.sip().method()).matches("^[A-Z]{3,}$"); + } + + @Test + public void contentType_returnLowerCaseTwoWordsSepereatedBySlashMinimum3And4Chars() { + assertThat(faker.sip().contentType()).matches("^[a-z]{4,}[/]{1,}[a-z0-9-]{3,}$"); + } + + @Test + public void messagingPort_return4DigitIntBetween1000And9999() { + assertThat(faker.sip().messagingPort()).isGreaterThanOrEqualTo(1000).isLessThan(10000); + } + + @Test + public void rtpPort_returnPositiveEvenInt() { + int sut = faker.sip().rtpPort(); + assertThat(sut).isGreaterThanOrEqualTo(2); + assertThat(sut % 2).isEqualTo(0); + } + + @Test + public void provisionalResponseCode_return3DigitIntBetween100And199() { + assertThat(faker.sip().provisionalResponseCode()).isGreaterThanOrEqualTo(100).isLessThan(200); + } + + @Test + public void successResponse_Codereturn3DigitIntBetween200And299() { + assertThat(faker.sip().successResponseCode()).isGreaterThanOrEqualTo(200).isLessThan(300); + } + + @Test + public void redirectResponseCode_Codereturn3DigitIntBetween300And399() { + assertThat(faker.sip().redirectResponseCode()).isGreaterThanOrEqualTo(300).isLessThan(400); + } + + @Test + public void clientErrorResponseCode_Codereturn3DigitIntBetween400And499() { + assertThat(faker.sip().clientErrorResponseCode()).isGreaterThanOrEqualTo(400).isLessThan(500); + } + + @Test + public void serverErrorResponseCode_Codereturn3DigitIntBetween500And599() { + assertThat(faker.sip().serverErrorResponseCode()).isGreaterThanOrEqualTo(500).isLessThan(600); + } + + @Test + public void globalErrorResponseCode_Codereturn3DigitIntBetween600And699() { + assertThat(faker.sip().globalErrorResponseCode()).isGreaterThanOrEqualTo(600).isLessThan(700); + } + + @Test + public void provisionalResponsePhrase_returnAnyNonDigitString() { + assertThat(faker.sip().provisionalResponsePhrase()).matches("\\D+"); + } + + @Test + public void successResponsePhrase_returnAnyNonDigitString() { + assertThat(faker.sip().successResponsePhrase()).matches("\\D+"); + } + + @Test + public void redirectResponsePhrase_returnAnyNonDigitString() { + assertThat(faker.sip().redirectResponsePhrase()).matches("\\D+"); + } + + @Test + public void clientErrorResponsePhrase_returnAnyNonDigitString() { + assertThat(faker.sip().clientErrorResponsePhrase()).matches("\\D+"); + } + + @Test + public void serverErrorResponsePhrase_returnAnyNonDigitString() { + assertThat(faker.sip().serverErrorResponsePhrase()).matches("\\D+"); + } + + @Test + public void globalErrorResponsePhrase_returnAnyNonDigitString() { + assertThat(faker.sip().globalErrorResponsePhrase()).matches("\\D+"); + } + + @Test + public void bodyString_returnAValidSdpBodyString() { + String[] sut = faker.sip().bodyString().split("\n"); + + assertThat(sut.length).isEqualTo(7); + + assertThat(sut[0]).isEqualTo("v=0"); + + String[] secondLine = sut[1].split(" "); + assertThat(secondLine[0]).startsWith("o="); + assertThat(secondLine[1]) + .matches("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"); + assertThat(secondLine[secondLine.length - 1]).matches("[a-z]+\\.\\w{2,4}"); + + assertThat(sut[2]).isEqualTo("s=-"); + + String[] fourthLine = sut[3].split(" "); + assertThat(fourthLine[0]).isEqualTo("c=IN"); + assertThat(fourthLine[fourthLine.length - 1]).matches("^\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}$"); + + assertThat(sut[4]).isEqualTo("t=0 0"); + + String[] sixthLine = sut[5].split(" "); + assertThat(sixthLine[0]).isEqualTo("m=audio"); + assertThat(Integer.parseInt(sixthLine[1])).isGreaterThanOrEqualTo(2); + assertThat(Integer.parseInt(sixthLine[1]) % 2).isEqualTo(0); + + assertThat(sut[6]).isEqualTo("a=rtpmap:0 PCMU/8000"); + } + + @Test + public void bodyBytes_isNotNull() { + byte[] sut = faker.sip().bodyBytes(); + + assertThat(sut.length).isNotNull(); + } + + @Test + public void nameAddress_returnValidNameAddressString() { + String[] sut = faker.sip().nameAddress().split("@"); + + assertThat(sut[0].split(":")[1]).matches("\\w+"); + assertThat(sut[1].split(":")[0]).matches("^\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}$"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/SlackEmojiTest.java b/src/test/java/org/thejavaguy/javafaker/SlackEmojiTest.java index 8cd729e..5c0e0c0 100644 --- a/src/test/java/org/thejavaguy/javafaker/SlackEmojiTest.java +++ b/src/test/java/org/thejavaguy/javafaker/SlackEmojiTest.java @@ -6,50 +6,50 @@ public class SlackEmojiTest extends AbstractFakerTest { - private static final String EMOTICON_REGEX = ":([\\w-]+):"; - - @Test - public void people() { - assertThat(faker.slackEmoji().people()).matches(EMOTICON_REGEX); - } - - @Test - public void nature() { - assertThat(faker.slackEmoji().nature()).matches(EMOTICON_REGEX); - } - - @Test - public void food_and_drink() { - assertThat(faker.slackEmoji().foodAndDrink()).matches(EMOTICON_REGEX); - } - - @Test - public void celebration() { - assertThat(faker.slackEmoji().celebration()).matches(EMOTICON_REGEX); - } - - @Test - public void activity() { - assertThat(faker.slackEmoji().activity()).matches(EMOTICON_REGEX); - } - - @Test - public void travel_and_places() { - assertThat(faker.slackEmoji().travelAndPlaces()).matches(EMOTICON_REGEX); - } - - @Test - public void objects_and_symbols() { - assertThat(faker.slackEmoji().objectsAndSymbols()).matches(EMOTICON_REGEX); - } - - @Test - public void custom() { - assertThat(faker.slackEmoji().custom()).matches(EMOTICON_REGEX); - } - - @Test - public void emoji() { - assertThat(faker.slackEmoji().emoji()).matches(EMOTICON_REGEX); - } + private static final String EMOTICON_REGEX = ":([\\w-]+):"; + + @Test + public void people() { + assertThat(faker.slackEmoji().people()).matches(EMOTICON_REGEX); + } + + @Test + public void nature() { + assertThat(faker.slackEmoji().nature()).matches(EMOTICON_REGEX); + } + + @Test + public void food_and_drink() { + assertThat(faker.slackEmoji().foodAndDrink()).matches(EMOTICON_REGEX); + } + + @Test + public void celebration() { + assertThat(faker.slackEmoji().celebration()).matches(EMOTICON_REGEX); + } + + @Test + public void activity() { + assertThat(faker.slackEmoji().activity()).matches(EMOTICON_REGEX); + } + + @Test + public void travel_and_places() { + assertThat(faker.slackEmoji().travelAndPlaces()).matches(EMOTICON_REGEX); + } + + @Test + public void objects_and_symbols() { + assertThat(faker.slackEmoji().objectsAndSymbols()).matches(EMOTICON_REGEX); + } + + @Test + public void custom() { + assertThat(faker.slackEmoji().custom()).matches(EMOTICON_REGEX); + } + + @Test + public void emoji() { + assertThat(faker.slackEmoji().emoji()).matches(EMOTICON_REGEX); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/SpaceTest.java b/src/test/java/org/thejavaguy/javafaker/SpaceTest.java index 0e5ffe2..e0bf5be 100644 --- a/src/test/java/org/thejavaguy/javafaker/SpaceTest.java +++ b/src/test/java/org/thejavaguy/javafaker/SpaceTest.java @@ -6,68 +6,68 @@ public class SpaceTest extends AbstractFakerTest { - @Test - public void planet() { - assertThat(faker.space().planet()).matches("(\\w+ ?){2,3}"); - } - - @Test - public void moon() { - assertThat(faker.space().moon()).matches("(\\w+ ?){2,3}"); - } - - @Test - public void galaxy() { - assertThat(faker.space().galaxy()).matches("(\\w+ ?){2,3}"); - } - - @Test - public void nebula() { - assertThat(faker.space().nebula()).matches("(\\w+ ?){2,3}"); - } - - @Test - public void starCluster() { - assertThat(faker.space().starCluster()).matches("(\\w+[ -]?){1,3}"); - } - - @Test - public void constellation() { - assertThat(faker.space().constellation()).matches("(\\w+ ?){2,3}"); - } - - @Test - public void star() { - assertThat(faker.space().star()).matches("(\\w+[ -]?){2,3}"); - } - - @Test - public void agency() { - assertThat(faker.space().agency()).matches("(\\w+ ?){2,5}"); - } - - @Test - public void agencyAbbreviation() { - assertThat(faker.space().agencyAbbreviation()).matches("(\\w+ ?){2,3}"); - } - - @Test - public void nasaSpaceCraft() { - assertThat(faker.space().nasaSpaceCraft()).matches("(\\w+ ?){2,3}"); - } - - @Test - public void company() { - assertThat(faker.space().company()).matches("((\\w|')+ ?){2,4}"); - } - - @Test - public void distanceMeasurement() { - assertThat(faker.space().distanceMeasurement()).matches("(\\w+ ?){2,3}"); - } - - @Test - public void meteorite() { - assertThat(faker.space().meteorite()).matches("(?U)([\\w()]+[ -–]?){1,4}"); - } + @Test + public void planet() { + assertThat(faker.space().planet()).matches("(\\w+ ?){2,3}"); + } + + @Test + public void moon() { + assertThat(faker.space().moon()).matches("(\\w+ ?){2,3}"); + } + + @Test + public void galaxy() { + assertThat(faker.space().galaxy()).matches("(\\w+ ?){2,3}"); + } + + @Test + public void nebula() { + assertThat(faker.space().nebula()).matches("(\\w+ ?){2,3}"); + } + + @Test + public void starCluster() { + assertThat(faker.space().starCluster()).matches("(\\w+[ -]?){1,3}"); + } + + @Test + public void constellation() { + assertThat(faker.space().constellation()).matches("(\\w+ ?){2,3}"); + } + + @Test + public void star() { + assertThat(faker.space().star()).matches("(\\w+[ -]?){2,3}"); + } + + @Test + public void agency() { + assertThat(faker.space().agency()).matches("(\\w+ ?){2,5}"); + } + + @Test + public void agencyAbbreviation() { + assertThat(faker.space().agencyAbbreviation()).matches("(\\w+ ?){2,3}"); + } + + @Test + public void nasaSpaceCraft() { + assertThat(faker.space().nasaSpaceCraft()).matches("(\\w+ ?){2,3}"); + } + + @Test + public void company() { + assertThat(faker.space().company()).matches("((\\w|')+ ?){2,4}"); + } + + @Test + public void distanceMeasurement() { + assertThat(faker.space().distanceMeasurement()).matches("(\\w+ ?){2,3}"); + } + + @Test + public void meteorite() { + assertThat(faker.space().meteorite()).matches("(?U)([\\w()]+[ -–]?){1,4}"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/StarCraftTest.java b/src/test/java/org/thejavaguy/javafaker/StarCraftTest.java index fa60299..4995115 100644 --- a/src/test/java/org/thejavaguy/javafaker/StarCraftTest.java +++ b/src/test/java/org/thejavaguy/javafaker/StarCraftTest.java @@ -6,34 +6,33 @@ public class StarCraftTest extends AbstractFakerTest { - private final String noLeadingTrailingWhitespaceRegex = "^(?! )[A-Za-z0-9' ]*(? Exceptions. - * In the case of 'pt', city_prefix is '' by design. This test fails because it's testing that all string returning - * methods return a non blank string. But pt city_prefix is blank ,but the test shouldn't fail. So we add put - * exceptions like this into this collection. - */ - private static final Map> exceptions = Maps.newHashMap(); - static { - // 'it' has an empty suffix list so it never returns a value - exceptions.put(new Locale("it"), Arrays.asList("Name.suffix")); - exceptions.put(new Locale("es-mx"), Arrays.asList("Address.cityPrefix", "Address.citySuffix")); - exceptions.put(new Locale("pt"), Arrays.asList("Address.cityPrefix", "Address.citySuffix")); - exceptions.put(new Locale("uk"), Arrays.asList("Address.stateAbbr", "Address.streetSuffix", - "Address.cityPrefix", "Address.citySuffix")); - exceptions.put(new Locale("pt-BR"), Arrays.asList("Address.cityPrefix", "Address.citySuffix")); - exceptions.put(new Locale("pt-br"), Arrays.asList("Address.cityPrefix", "Address.citySuffix")); - exceptions.put(new Locale("Pt_br"), Arrays.asList("Address.cityPrefix", "Address.citySuffix")); - exceptions.put(new Locale("pT_Br"), Arrays.asList("Address.cityPrefix", "Address.citySuffix")); - exceptions.put(new Locale("pt","Br", "x2"), Arrays.asList("Address.cityPrefix", "Address.citySuffix")); + private static final Logger logger = LoggerFactory.getLogger(FakerIT.class); + private Locale locale; + private Faker faker; + + /** + * a collection of Locales -> Exceptions. In the case of 'pt', city_prefix is '' by design. This + * test fails because it's testing that all string returning methods return a non blank string. + * But pt city_prefix is blank ,but the test shouldn't fail. So we add put exceptions like this + * into this collection. + */ + private static final Map> exceptions = Maps.newHashMap(); + + static { + // 'it' has an empty suffix list so it never returns a value + exceptions.put(new Locale("it"), Arrays.asList("Name.suffix")); + exceptions.put(new Locale("es-mx"), Arrays.asList("Address.cityPrefix", "Address.citySuffix")); + exceptions.put(new Locale("pt"), Arrays.asList("Address.cityPrefix", "Address.citySuffix")); + exceptions.put( + new Locale("uk"), + Arrays.asList( + "Address.stateAbbr", + "Address.streetSuffix", + "Address.cityPrefix", + "Address.citySuffix")); + exceptions.put(new Locale("pt-BR"), Arrays.asList("Address.cityPrefix", "Address.citySuffix")); + exceptions.put(new Locale("pt-br"), Arrays.asList("Address.cityPrefix", "Address.citySuffix")); + exceptions.put(new Locale("Pt_br"), Arrays.asList("Address.cityPrefix", "Address.citySuffix")); + exceptions.put(new Locale("pT_Br"), Arrays.asList("Address.cityPrefix", "Address.citySuffix")); + exceptions.put( + new Locale("pt", "Br", "x2"), Arrays.asList("Address.cityPrefix", "Address.citySuffix")); + } + + public void initFakerIT(Locale locale, Random random) { + this.locale = locale; + if (locale != null && random != null) { + faker = new Faker(locale, random); + } else if (locale != null) { + faker = new Faker(locale); + } else if (random != null) { + faker = new Faker(random); + } else { + faker = new Faker(); } - - public void initFakerIT(Locale locale, Random random) { - this.locale = locale; - if (locale != null && random != null) { - faker = new Faker(locale, random); - } else if (locale != null) { - faker = new Faker(locale); - } else if (random != null) { - faker = new Faker(random); - } else { - faker = new Faker(); - } + } + + public static Collection data() { + Object[][] data = + new Object[][] { + {Locale.ENGLISH, new Random()}, + {new Locale("pt-BR"), null}, + {new Locale("pt-br"), null}, + {new Locale("Pt_br"), null}, + {new Locale("pT_Br"), null}, + {new Locale("pt", "Br", "x2"), null}, + {null, new Random()}, + {null, null} + }; + + String[] ymlFiles = new File("./src/main/resources").list(); + int numberOfYmlFiles = ymlFiles.length; + Object[][] dataFromYmlFiles = new Object[numberOfYmlFiles][2]; + for (int i = 0; i < numberOfYmlFiles; i++) { + String ymlFileName = ymlFiles[i]; + dataFromYmlFiles[i][0] = new Locale(StringUtils.substringBefore(ymlFileName, ".")); } - public static Collection data() { - Object[][] data = new Object[][]{ - {Locale.ENGLISH, new Random()}, - {new Locale("pt-BR"), null}, - {new Locale("pt-br"), null}, - {new Locale("Pt_br"), null}, - {new Locale("pT_Br"), null}, - {new Locale("pt","Br","x2"), null}, - {null, new Random()}, - {null, null}}; - - String[] ymlFiles = new File("./src/main/resources").list(); - int numberOfYmlFiles = ymlFiles.length; - Object[][] dataFromYmlFiles = new Object[numberOfYmlFiles][2]; - for (int i = 0; i < numberOfYmlFiles; i++) { - String ymlFileName = ymlFiles[i]; - dataFromYmlFiles[i][0] = new Locale(StringUtils.substringBefore(ymlFileName, ".")); - } - - List allData = new ArrayList<>(Arrays.asList(data)); - allData.addAll(Arrays.asList(dataFromYmlFiles)); - return allData; + List allData = new ArrayList<>(Arrays.asList(data)); + allData.addAll(Arrays.asList(dataFromYmlFiles)); + return allData; + } + + @MethodSource("data") + @ParameterizedTest(name = "testing locale {0} and random {1}") + public void testAllFakerMethodsThatReturnStrings(Locale locale, Random random) throws Exception { + initFakerIT(locale, random); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.ancient()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.address()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.app()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.artist()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.aviation()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.backToTheFuture()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.business()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.book()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.chuckNorris()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.color()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.commerce()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.company()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.country()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.crypto()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.demographic()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.dragonBall()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.dog()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.educator()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.funnyName()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.hitchhikersGuideToTheGalaxy()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.hobbit()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.howIMetYourMother()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.internet()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.leagueOfLegends()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.lorem()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.overwatch()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.phoneNumber()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.pokemon()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.robin()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.starTrek()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.music()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.name()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.file()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.finance()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.food()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.gameOfThrones()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.gender()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.hacker()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.idNumber()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.shakespeare()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.slackEmoji()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.space()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.stock()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.superhero()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.team()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.beer()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.coin()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.university()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.cat()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.lordOfTheRings()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.zelda()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.harryPotter()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.rockBand()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.esports()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.friends()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.hipster()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.job()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.twinPeaks()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.rickAndMorty()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.yoda()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.matz()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.witcher()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.weather()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.lebowski()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.animal()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.princessBride()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.elderScrolls()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.buffy()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.relationships()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.nation()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.dune()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.aquaTeenHungerForce()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.programmingLanguage()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.kaamelott()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.photography()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.starCraft()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.bojackHorseman()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.disease()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.basketball()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.barcode()); + testAllMethodsThatReturnStringsActuallyReturnStrings(faker.englandfootball()); + } + + private void testAllMethodsThatReturnStringsActuallyReturnStrings(Object object) + throws Exception { + @SuppressWarnings("unchecked") + Set methodsThatReturnStrings = + getAllMethods( + object.getClass(), + withModifier(Modifier.PUBLIC), + withReturnType(String.class), + withParametersCount(0)); + + for (Method method : methodsThatReturnStrings) { + if (isExcepted(object, method)) { + continue; + } + final Object returnValue = method.invoke(object); + logger.info( + "{} {}.{} = {}", + locale, + object.getClass().getSimpleName().toLowerCase(), + method.getName(), + returnValue); + String failureReason = method + " on " + object; + assertThat(returnValue).as(failureReason).isInstanceOf(String.class); + final String returnValueAsString = (String) returnValue; + assertThat(returnValueAsString).as(failureReason).isNotEmpty(); + assertThat(returnValueAsString) + .as(failureReason + " is a slash encoded regex") + .doesNotMatch("^/.*/$"); } + } - @MethodSource("data") - @ParameterizedTest(name = "testing locale {0} and random {1}") - public void testAllFakerMethodsThatReturnStrings(Locale locale,Random random) throws Exception { - initFakerIT(locale, random); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.ancient()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.address()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.app()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.artist()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.aviation()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.backToTheFuture()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.business()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.book()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.chuckNorris()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.color()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.commerce()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.company()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.country()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.crypto()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.demographic()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.dragonBall()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.dog()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.educator()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.funnyName()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.hitchhikersGuideToTheGalaxy()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.hobbit()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.howIMetYourMother()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.internet()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.leagueOfLegends()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.lorem()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.overwatch()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.phoneNumber()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.pokemon()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.robin()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.starTrek()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.music()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.name()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.file()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.finance()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.food()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.gameOfThrones()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.gender()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.hacker()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.idNumber()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.shakespeare()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.slackEmoji()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.space()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.stock()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.superhero()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.team()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.beer()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.coin()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.university()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.cat()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.lordOfTheRings()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.zelda()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.harryPotter()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.rockBand()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.esports()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.friends()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.hipster()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.job()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.twinPeaks()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.rickAndMorty()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.yoda()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.matz()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.witcher()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.weather()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.lebowski()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.animal()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.princessBride()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.elderScrolls()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.buffy()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.relationships()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.nation()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.dune()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.aquaTeenHungerForce()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.programmingLanguage()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.kaamelott()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.photography()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.starCraft()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.bojackHorseman()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.disease()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.basketball()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.barcode()); - testAllMethodsThatReturnStringsActuallyReturnStrings(faker.englandfootball()); + private boolean isExcepted(Object object, Method method) { + final List classDotMethod = exceptions.get(this.locale); + if (classDotMethod == null) { + return false; } + return classDotMethod.contains(object.getClass().getSimpleName() + "." + method.getName()); + } - private void testAllMethodsThatReturnStringsActuallyReturnStrings(Object object) throws Exception { - @SuppressWarnings("unchecked") - Set methodsThatReturnStrings = getAllMethods(object.getClass(), - withModifier(Modifier.PUBLIC), - withReturnType(String.class), - withParametersCount(0)); - - for (Method method : methodsThatReturnStrings) { - if (isExcepted(object, method)) { - continue; - } - final Object returnValue = method.invoke(object); - logger.info("{} {}.{} = {}", locale, object.getClass().getSimpleName().toLowerCase(), method.getName(), returnValue); - String failureReason = method + " on " + object; - assertThat(returnValue).as(failureReason).isInstanceOf(String.class); - final String returnValueAsString = (String) returnValue; - assertThat(returnValueAsString).as(failureReason).isNotEmpty(); - assertThat(returnValueAsString) - .as(failureReason + " is a slash encoded regex") - .doesNotMatch("^/.*/$"); - } - } + @MethodSource("data") + @ParameterizedTest(name = "testing locale {0} and random {1}") + public void testExceptionsNotCoveredInAboveTest(Locale locale, Random random) { + initFakerIT(locale, random); + assertThat(faker.bothify("####???")).isNotNull(); + assertThat(faker.letterify("????")).isNotNull(); + assertThat(faker.numerify("####")).isNotNull(); - private boolean isExcepted(Object object, Method method) { - final List classDotMethod = exceptions.get(this.locale); - if (classDotMethod == null) {return false;} - return classDotMethod.contains(object.getClass().getSimpleName() + "." + method.getName()); - } - - @MethodSource("data") - @ParameterizedTest(name = "testing locale {0} and random {1}") - public void testExceptionsNotCoveredInAboveTest(Locale locale,Random random) { - initFakerIT(locale, random); - assertThat(faker.bothify("####???")).isNotNull(); - assertThat(faker.letterify("????")).isNotNull(); - assertThat(faker.numerify("####")).isNotNull(); - - assertThat(faker.lorem().paragraph(1)).isNotNull(); - assertThat(faker.lorem().paragraphs(1)).isNotNull(); + assertThat(faker.lorem().paragraph(1)).isNotNull(); + assertThat(faker.lorem().paragraphs(1)).isNotNull(); - assertThat(faker.lorem().sentence(1)).isNotNull(); - assertThat(faker.lorem().sentences(1)).isNotNull(); + assertThat(faker.lorem().sentence(1)).isNotNull(); + assertThat(faker.lorem().sentences(1)).isNotNull(); - assertThat(faker.address().streetAddress()).isNotNull(); - - assertThat(faker.lorem().words()).isNotNull(); - assertThat(faker.lorem().words(1)).isNotNull(); - } + assertThat(faker.address().streetAddress()).isNotNull(); + assertThat(faker.lorem().words()).isNotNull(); + assertThat(faker.lorem().words(1)).isNotNull(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/integration/Issue194SlashFormatRegexIT.java b/src/test/java/org/thejavaguy/javafaker/integration/Issue194SlashFormatRegexIT.java index b0a5c7d..f3c0797 100644 --- a/src/test/java/org/thejavaguy/javafaker/integration/Issue194SlashFormatRegexIT.java +++ b/src/test/java/org/thejavaguy/javafaker/integration/Issue194SlashFormatRegexIT.java @@ -3,7 +3,6 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.Locale; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.thejavaguy.javafaker.Faker; @@ -11,30 +10,35 @@ @Disabled public class Issue194SlashFormatRegexIT { - @Test - public void enGBZipCodeReturnsProperRegexifiedValue() { - final Locale uk = new Locale("en-GB"); + @Test + public void enGBZipCodeReturnsProperRegexifiedValue() { + final Locale uk = new Locale("en-GB"); - final String postalCode = new Faker(uk).address().zipCode(); + final String postalCode = new Faker(uk).address().zipCode(); - assertThat(postalCode).matches("[A-PR-UWYZ]([A-HK-Y][0-9][ABEHMNPRVWXY0-9]?|[0-9][ABCDEFGHJKPSTUW0-9]?) [0-9][ABD-HJLNP-UW-Z]{2}"); - } + assertThat(postalCode) + .matches( + "[A-PR-UWYZ]([A-HK-Y][0-9][ABEHMNPRVWXY0-9]?|[0-9][ABCDEFGHJKPSTUW0-9]?) [0-9][ABD-HJLNP-UW-Z]{2}"); + } - @Test - public void enCAZipCodeReturnsProperRegexifiedValue() { - final Locale uk = new Locale("en-CA"); + @Test + public void enCAZipCodeReturnsProperRegexifiedValue() { + final Locale uk = new Locale("en-CA"); - final String postalCode = new Faker(uk).address().zipCode(); + final String postalCode = new Faker(uk).address().zipCode(); - assertThat(postalCode).matches("[A-CEJ-NPR-TVXY][0-9][A-CEJ-NPR-TV-Z] ?[0-9][A-CEJ-NPR-TV-Z][0-9]"); - } + assertThat(postalCode) + .matches("[A-CEJ-NPR-TVXY][0-9][A-CEJ-NPR-TV-Z] ?[0-9][A-CEJ-NPR-TV-Z][0-9]"); + } - @Test - public void viZipCodeReturnsProperRegexifiedValue() { - final Locale uk = new Locale("vi"); + @Test + public void viZipCodeReturnsProperRegexifiedValue() { + final Locale uk = new Locale("vi"); - final String postalCode = new Faker(uk).address().zipCode(); + final String postalCode = new Faker(uk).address().zipCode(); - assertThat(postalCode).matches("[A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}"); - } + assertThat(postalCode) + .matches( + "[A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}"); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/integration/MostSpecificLocaleIT.java b/src/test/java/org/thejavaguy/javafaker/integration/MostSpecificLocaleIT.java index ae89f3e..1fdf87d 100644 --- a/src/test/java/org/thejavaguy/javafaker/integration/MostSpecificLocaleIT.java +++ b/src/test/java/org/thejavaguy/javafaker/integration/MostSpecificLocaleIT.java @@ -4,38 +4,41 @@ import java.util.List; import java.util.Locale; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.thejavaguy.javafaker.service.FakeValuesService; /** - * The purpose of these tests is to ensure that the Locales have been properly configured - * and that methods return values. The unit tests should ensure what the values returned - * are correct. These tests just ensure that the methods can be invoked. + * The purpose of these tests is to ensure that the Locales have been properly configured and that + * methods return values. The unit tests should ensure what the values returned are correct. These + * tests just ensure that the methods can be invoked. */ @Disabled public class MostSpecificLocaleIT { - private FakeValuesService en; - private FakeValuesService en_US; - - @BeforeEach - public void setupFakers() { - en = new FakeValuesService(new Locale("en"), null); - en_US = new FakeValuesService(new Locale("en","US"), null); - } - - @Test - @SuppressWarnings("unchecked") - public void resolvesTheMostSpecificLocale() { - final List enDefaultCountries = (List) en.fetchObject("address.default_country"); - final List enUsDefaultCountries = (List) en_US.fetchObject("address.default_country"); - - assertThat(enDefaultCountries).hasSize(1); - assertThat(enUsDefaultCountries).hasSize(3); - - assertThat(enDefaultCountries).as("the default country for en is not en_US").isNotEqualTo(enUsDefaultCountries); - } + private FakeValuesService en; + private FakeValuesService en_US; + + @BeforeEach + public void setupFakers() { + en = new FakeValuesService(new Locale("en"), null); + en_US = new FakeValuesService(new Locale("en", "US"), null); + } + + @Test + @SuppressWarnings("unchecked") + public void resolvesTheMostSpecificLocale() { + final List enDefaultCountries = + (List) en.fetchObject("address.default_country"); + final List enUsDefaultCountries = + (List) en_US.fetchObject("address.default_country"); + + assertThat(enDefaultCountries).hasSize(1); + assertThat(enUsDefaultCountries).hasSize(3); + + assertThat(enDefaultCountries) + .as("the default country for en is not en_US") + .isNotEqualTo(enUsDefaultCountries); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/integration/UkLocalDirectivesTest.java b/src/test/java/org/thejavaguy/javafaker/integration/UkLocalDirectivesTest.java index b40f2f9..8accc90 100644 --- a/src/test/java/org/thejavaguy/javafaker/integration/UkLocalDirectivesTest.java +++ b/src/test/java/org/thejavaguy/javafaker/integration/UkLocalDirectivesTest.java @@ -2,50 +2,47 @@ import static org.assertj.core.api.Assertions.assertThat; +import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.Locale; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.thejavaguy.javafaker.Faker; -import com.google.common.collect.Lists; - /** - * The purpose of these tests is to ensure that the Locales have been properly configured - * and that methods return values. The unit tests should ensure what the values returned - * are correct. These tests just ensure that the methods can be invoked. + * The purpose of these tests is to ensure that the Locales have been properly configured and that + * methods return values. The unit tests should ensure what the values returned are correct. These + * tests just ensure that the methods can be invoked. */ @Disabled public class UkLocalDirectivesTest { - /** - * uk is interesting in that it has feminine and masculine prefixes for street names. the feminine - * and masculine prefixes are NOT methods on Address though as they only make sense for this locale (and possibly - * others). This test shows we can resolve within the yml file without reaching out to any of the {@link Faker} - * child objects. - */ - @Test - public void resolvesDirectivesOnlyInYmlFile() { - final Locale uk = new Locale("uk"); + /** + * uk is interesting in that it has feminine and masculine prefixes for street names. the feminine + * and masculine prefixes are NOT methods on Address though as they only make sense for this + * locale (and possibly others). This test shows we can resolve within the yml file without + * reaching out to any of the {@link Faker} child objects. + */ + @Test + public void resolvesDirectivesOnlyInYmlFile() { + final Locale uk = new Locale("uk"); - final String streetName = new Faker(uk).address().streetName(); + final String streetName = new Faker(uk).address().streetName(); - final ArrayList masc = Lists.newArrayList("пр.", "проспект", "пров.", "провулок"); - final ArrayList fem = Lists.newArrayList("вул.", "вулиця", "пл.", "площа"); + final ArrayList masc = Lists.newArrayList("пр.", "проспект", "пров.", "провулок"); + final ArrayList fem = Lists.newArrayList("вул.", "вулиця", "пл.", "площа"); - boolean startsWithMascPrefix = false, - startsWithFemPrefix = false; + boolean startsWithMascPrefix = false, startsWithFemPrefix = false; - for (String mascPrefix : masc) { - startsWithMascPrefix |= streetName.startsWith(mascPrefix); - } - for (String femPrefix : fem) { - startsWithFemPrefix |= streetName.startsWith(femPrefix); - } - - assertThat(startsWithFemPrefix || startsWithMascPrefix).as("the streetname starts with a fem or masc prefix").isEqualTo(true); + for (String mascPrefix : masc) { + startsWithMascPrefix |= streetName.startsWith(mascPrefix); + } + for (String femPrefix : fem) { + startsWithFemPrefix |= streetName.startsWith(femPrefix); } - + assertThat(startsWithFemPrefix || startsWithMascPrefix) + .as("the streetname starts with a fem or masc prefix") + .isEqualTo(true); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/repeating/Repeat.java b/src/test/java/org/thejavaguy/javafaker/repeating/Repeat.java index d117677..ab50c45 100644 --- a/src/test/java/org/thejavaguy/javafaker/repeating/Repeat.java +++ b/src/test/java/org/thejavaguy/javafaker/repeating/Repeat.java @@ -3,13 +3,10 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Pulled from fappel - */ -@Retention( RetentionPolicy.RUNTIME ) -@Target( { - java.lang.annotation.ElementType.METHOD -} ) + +/** Pulled from fappel */ +@Retention(RetentionPolicy.RUNTIME) +@Target({java.lang.annotation.ElementType.METHOD}) public @interface Repeat { int times(); } diff --git a/src/test/java/org/thejavaguy/javafaker/repeating/RepeatRule.java b/src/test/java/org/thejavaguy/javafaker/repeating/RepeatRule.java index e5b20fa..48f81df 100644 --- a/src/test/java/org/thejavaguy/javafaker/repeating/RepeatRule.java +++ b/src/test/java/org/thejavaguy/javafaker/repeating/RepeatRule.java @@ -2,47 +2,49 @@ import java.util.stream.IntStream; import java.util.stream.Stream; - import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.TestTemplateInvocationContext; import org.junit.jupiter.api.extension.TestTemplateInvocationContextProvider; /** - * JUnit 5 extension that provides repeated test execution based on the @Repeat annotation. - * Migrated from JUnit 4 TestRule to JUnit 5 TestTemplateInvocationContextProvider. + * JUnit 5 extension that provides repeated test execution based on the @Repeat annotation. Migrated + * from JUnit 4 TestRule to JUnit 5 TestTemplateInvocationContextProvider. */ public class RepeatRule implements TestTemplateInvocationContextProvider { - @Override - public boolean supportsTestTemplate(ExtensionContext context) { - return context.getTestMethod() - .map(method -> method.isAnnotationPresent(Repeat.class)) - .orElse(false); + @Override + public boolean supportsTestTemplate(ExtensionContext context) { + return context + .getTestMethod() + .map(method -> method.isAnnotationPresent(Repeat.class)) + .orElse(false); + } + + @Override + public Stream provideTestTemplateInvocationContexts( + ExtensionContext context) { + int times = + context + .getTestMethod() + .map(method -> method.getAnnotation(Repeat.class)) + .map(Repeat::times) + .orElse(1); + + return IntStream.rangeClosed(1, times).mapToObj(i -> new RepeatInvocationContext(i, times)); + } + + private static class RepeatInvocationContext implements TestTemplateInvocationContext { + private final int currentRepetition; + private final int totalRepetitions; + + RepeatInvocationContext(int currentRepetition, int totalRepetitions) { + this.currentRepetition = currentRepetition; + this.totalRepetitions = totalRepetitions; } @Override - public Stream provideTestTemplateInvocationContexts(ExtensionContext context) { - int times = context.getTestMethod() - .map(method -> method.getAnnotation(Repeat.class)) - .map(Repeat::times) - .orElse(1); - - return IntStream.rangeClosed(1, times) - .mapToObj(i -> new RepeatInvocationContext(i, times)); - } - - private static class RepeatInvocationContext implements TestTemplateInvocationContext { - private final int currentRepetition; - private final int totalRepetitions; - - RepeatInvocationContext(int currentRepetition, int totalRepetitions) { - this.currentRepetition = currentRepetition; - this.totalRepetitions = totalRepetitions; - } - - @Override - public String getDisplayName(int invocationIndex) { - return "repetition " + currentRepetition + " of " + totalRepetitions; - } + public String getDisplayName(int invocationIndex) { + return "repetition " + currentRepetition + " of " + totalRepetitions; } + } } diff --git a/src/test/java/org/thejavaguy/javafaker/service/FakeValuesGroupingTest.java b/src/test/java/org/thejavaguy/javafaker/service/FakeValuesGroupingTest.java index 27a2af0..22bfdcc 100644 --- a/src/test/java/org/thejavaguy/javafaker/service/FakeValuesGroupingTest.java +++ b/src/test/java/org/thejavaguy/javafaker/service/FakeValuesGroupingTest.java @@ -3,37 +3,36 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.Locale; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class FakeValuesGroupingTest { - private FakeValuesGrouping fakeValuesGrouping; - private FakeValues addressValues; - - @BeforeEach - public void before() { - fakeValuesGrouping = new FakeValuesGrouping(); - addressValues = new FakeValues(Locale.ENGLISH, "address.yml", "address"); - fakeValuesGrouping.add(addressValues); - } - - @Test - public void handlesOneFakeValue() { - assertThat(fakeValuesGrouping.get("address")).isEqualTo(addressValues.get("address")); - assertThat(fakeValuesGrouping.get("address")).isNotNull(); - } - - @Test - public void handlesMultipleFakeValues() { - FakeValues catValues = new FakeValues(Locale.ENGLISH, "cat.yml", "creature"); - fakeValuesGrouping.add(catValues); - - assertThat(fakeValuesGrouping.get("address")).isEqualTo(addressValues.get("address")); - assertThat(fakeValuesGrouping.get("address")).isNotNull(); - - assertThat(fakeValuesGrouping.get("creature")).isEqualTo(catValues.get("creature")); - assertThat(fakeValuesGrouping.get("creature")).isNotNull(); - } + private FakeValuesGrouping fakeValuesGrouping; + private FakeValues addressValues; + + @BeforeEach + public void before() { + fakeValuesGrouping = new FakeValuesGrouping(); + addressValues = new FakeValues(Locale.ENGLISH, "address.yml", "address"); + fakeValuesGrouping.add(addressValues); + } + + @Test + public void handlesOneFakeValue() { + assertThat(fakeValuesGrouping.get("address")).isEqualTo(addressValues.get("address")); + assertThat(fakeValuesGrouping.get("address")).isNotNull(); + } + + @Test + public void handlesMultipleFakeValues() { + FakeValues catValues = new FakeValues(Locale.ENGLISH, "cat.yml", "creature"); + fakeValuesGrouping.add(catValues); + + assertThat(fakeValuesGrouping.get("address")).isEqualTo(addressValues.get("address")); + assertThat(fakeValuesGrouping.get("address")).isNotNull(); + + assertThat(fakeValuesGrouping.get("creature")).isEqualTo(catValues.get("creature")); + assertThat(fakeValuesGrouping.get("creature")).isNotNull(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/service/FakeValuesServiceTest.java b/src/test/java/org/thejavaguy/javafaker/service/FakeValuesServiceTest.java index 30f4578..34ef8ae 100644 --- a/src/test/java/org/thejavaguy/javafaker/service/FakeValuesServiceTest.java +++ b/src/test/java/org/thejavaguy/javafaker/service/FakeValuesServiceTest.java @@ -16,7 +16,6 @@ import java.util.Date; import java.util.List; import java.util.Locale; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -29,309 +28,317 @@ public class FakeValuesServiceTest extends AbstractFakerTest { - private static final Long MILLIS_IN_AN_HOUR = 1000 * 60 * 60L; - private static final Long MILLIS_IN_A_DAY = MILLIS_IN_AN_HOUR * 24; - - @Mock - private RandomService randomService; - - private FakeValuesService fakeValuesService; - private AutoCloseable closeable; + private static final Long MILLIS_IN_AN_HOUR = 1000 * 60 * 60L; + private static final Long MILLIS_IN_A_DAY = MILLIS_IN_AN_HOUR * 24; + + @Mock private RandomService randomService; - @BeforeEach - public void before() { - super.before(); - closeable = MockitoAnnotations.openMocks(this); - - // always return the first element - when(randomService.nextInt(anyInt())).thenReturn(0); - - fakeValuesService = spy(new FakeValuesService(new Locale("test"), randomService)); + private FakeValuesService fakeValuesService; + private AutoCloseable closeable; + + @BeforeEach + public void before() { + super.before(); + closeable = MockitoAnnotations.openMocks(this); + + // always return the first element + when(randomService.nextInt(anyInt())).thenReturn(0); + + fakeValuesService = spy(new FakeValuesService(new Locale("test"), randomService)); + } + + @AfterEach + void closeMocks() throws Exception { + closeable.close(); + } + + @Test + public void fetchStringShouldReturnValue() { + assertThat(fakeValuesService.fetchString("property.dummy")).isEqualTo("x"); + } + + @Test + public void fetchShouldReturnValue() { + assertThat(fakeValuesService.fetch("property.dummy")).isEqualTo("x"); + } + + @Test + public void fetchObjectShouldReturnValue() { + assertThat(fakeValuesService.fetchObject("property.dummy")) + .isEqualTo(Arrays.asList("x", "y", "z")); + } + + @Test + public void safeFetchShouldReturnValueInList() { + doReturn(0).when(randomService).nextInt(Mockito.anyInt()); + assertThat(fakeValuesService.safeFetch("property.dummy", null)).isEqualTo("x"); + } + + @Test + public void safeFetchShouldReturnSimpleList() { + assertThat(fakeValuesService.safeFetch("property.simple", null)).isEqualTo("hello"); + } + + @Test + public void safeFetchShouldReturnEmptyStringWhenPropertyDoesntExist() { + assertThat(fakeValuesService.safeFetch("property.dummy2", "")).isEmpty(); + } + + @Test + public void bothify2Args() { + final DummyService dummy = mock(DummyService.class); + + Faker f = new Faker(); + + String value = fakeValuesService.resolve("property.bothify_2", dummy, f); + assertThat(value).matches("[A-Z]{2}\\d{2}"); + } + + @Test + public void regexifyDirective() { + final DummyService dummy = mock(DummyService.class); + + String value = fakeValuesService.resolve("property.regexify1", dummy, faker); + assertThat(value).isIn("55", "44", "45", "54"); + verify(faker).regexify("[45]{2}"); + } + + @Test + public void regexifySlashFormatDirective() { + final DummyService dummy = mock(DummyService.class); + + String value = fakeValuesService.resolve("property.regexify_slash_format", dummy, faker); + assertThat(value).isIn("55", "44", "45", "54"); + verify(faker).regexify("[45]{2}"); + } + + @Test + public void regexifyDirective2() { + final DummyService dummy = mock(DummyService.class); + + String value = fakeValuesService.resolve("property.regexify_cell", dummy, faker); + assertThat(value).isIn("479", "459"); + verify(faker).regexify("4[57]9"); + } + + @Test + public void resolveKeyToPropertyWithAPropertyWithoutAnObject() { + // #{hello} -> DummyService.hello + + // given + final DummyService dummy = mock(DummyService.class); + doReturn("Yo!").when(dummy).hello(); + + // when + final String actual = fakeValuesService.resolve("property.simpleResolution", dummy, faker); + + // then + assertThat(actual).isEqualTo("Yo!"); + verify(dummy).hello(); + verifyNoMoreInteractions(faker); + } + + @Test + public void resolveKeyToPropertyWithAPropertyWithAnObject() { + // given + final Superhero person = mock(Superhero.class); + final DummyService dummy = mock(DummyService.class); + doReturn(person).when(faker).superhero(); + doReturn("Luke Cage").when(person).name(); + + // when + final String actual = fakeValuesService.resolve("property.advancedResolution", dummy, faker); + + // then + assertThat(actual).isEqualTo("Luke Cage"); + verify(faker).superhero(); + verify(person).name(); + } + + @Test + public void resolveKeyToPropertyWithAList() { + // property.resolutionWithList -> #{hello} + // #{hello} -> DummyService.hello + + // given + final DummyService dummy = mock(DummyService.class); + doReturn(0).when(randomService).nextInt(Mockito.anyInt()); + doReturn("Yo!").when(dummy).hello(); + + // when + final String actual = fakeValuesService.resolve("property.resolutionWithList", dummy, faker); + + // then + assertThat(actual).isEqualTo("Yo!"); + verify(dummy).hello(); + } + + @Test + public void resolveKeyWithMultiplePropertiesShouldJoinResults() { + // given + final Superhero person = mock(Superhero.class); + final DummyService dummy = mock(DummyService.class); + doReturn(person).when(faker).superhero(); + + doReturn("Yo Superman!").when(dummy).hello(); + doReturn("up up and away").when(person).descriptor(); + + // when + String actual = fakeValuesService.resolve("property.multipleResolution", dummy, faker); + + // then + assertThat(actual).isEqualTo("Yo Superman! up up and away"); + + verify(faker).superhero(); + verify(person).descriptor(); + verify(dummy).hello(); + } + + @Test + public void testLocaleChain() { + final List chain = fakeValuesService.localeChain(Locale.SIMPLIFIED_CHINESE); + + assertThat(chain).containsExactly(Locale.SIMPLIFIED_CHINESE, Locale.CHINESE, Locale.ENGLISH); + } + + @Test + public void testLocaleChainEnglish() { + final List chain = fakeValuesService.localeChain(Locale.ENGLISH); + + assertThat(chain).containsExactly(Locale.ENGLISH); + } + + @Test + public void testLocaleChainLanguageOnly() { + final List chain = fakeValuesService.localeChain(Locale.CHINESE); + + assertThat(chain).containsExactly(Locale.CHINESE, Locale.ENGLISH); + } + + @Test + public void expressionWithInvalidFakerObject() { + expressionShouldFailWith( + "#{ObjectNotOnFaker.methodName}", + "Unable to resolve #{ObjectNotOnFaker.methodName} directive."); + } + + @Test + public void expressionWithValidFakerObjectButInvalidMethod() { + expressionShouldFailWith( + "#{Name.nonExistentMethod}", "Unable to resolve #{Name.nonExistentMethod} directive."); + } + + /** + * Two things are important here: 1) the message in the exception should be USEFUL 2) a {@link + * RuntimeException} should be thrown. + * + *

if the message changes, it's ok to update the test provided the two conditions above are + * still true. + */ + @Test + public void expressionWithValidFakerObjectValidMethodInvalidArgs() { + expressionShouldFailWith( + "#{Number.number_between 'x','y'}", + "Unable to resolve #{Number.number_between 'x','y'} directive."); + } + + @Test + public void futureDateExpression() throws ParseException { + SimpleDateFormat dateFormat = + new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH); + + Date now = new Date(); + Date nowPlus10Days = new Date(now.getTime() + MILLIS_IN_A_DAY * 10); + + Date date = + dateFormat.parse( + fakeValuesService.expression("#{date.future '10','TimeUnit.DAYS'}", faker)); + + assertThat(date.getTime()).isGreaterThan(now.getTime()); + assertThat(date.getTime()).isLessThan(nowPlus10Days.getTime()); + } + + @Test + public void pastDateExpression() throws ParseException { + SimpleDateFormat dateFormat = + new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH); + + Date now = new Date(); + Date nowMinus5Hours = new Date(now.getTime() - MILLIS_IN_AN_HOUR * 5); + + Date date = + dateFormat.parse(fakeValuesService.expression("#{date.past '5','TimeUnit.HOURS'}", faker)); + + assertThat(date.getTime()).isGreaterThan(nowMinus5Hours.getTime()); + assertThat(date.getTime()).isLessThan(now.getTime()); + } + + @Test + public void expressionWithFourArguments() throws ParseException { + + assertThat(fakeValuesService.expression("#{Internet.password '5','8','true','true'}", faker)) + .matches("[\\w\\d\\!%#$@_\\^&\\*]{5,8}"); + } + + /** + * Two things are important here: 1) the message in the exception should be USEFUL 2) a {@link + * RuntimeException} should be thrown. + * + *

if the message changes, it's ok to update the test provided the two conditions above are + * still true. + */ + @Test + public void expressionCompletelyUnresolvable() { + expressionShouldFailWith("#{x}", "Unable to resolve #{x} directive."); + } + + private void expressionShouldFailWith(String expression, String errorMessage) { + try { + fakeValuesService.expression(expression, faker); + fail("Should have failed with RuntimeException and message of " + errorMessage); + } catch (RuntimeException re) { + assertThat(re.getMessage()).isEqualTo(errorMessage); } - - @AfterEach - void closeMocks() throws Exception{ - closeable.close(); + } + + @Test + public void resolveUsingTheSameKeyTwice() { + // #{hello} -> DummyService.hello + + // given + final DummyService dummy = mock(DummyService.class); + when(dummy.hello()).thenReturn("1").thenReturn("2"); + + // when + final String actual = fakeValuesService.resolve("property.sameResolution", dummy, faker); + + // then + assertThat(actual).isEqualTo("1 2"); + verifyNoMoreInteractions(faker); + } + + @Test + public void FakeValuesServiceWithNullLocaleTest() { + try { + RandomService r = new RandomService(); + FakeValuesService f = new FakeValuesService(null, r); + fail("Should catch IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage()).isEqualTo("locale is required"); } + } - @Test - public void fetchStringShouldReturnValue() { - assertThat(fakeValuesService.fetchString("property.dummy")).isEqualTo("x"); + public static class DummyService { + public String firstName() { + return "John"; } - @Test - public void fetchShouldReturnValue() { - assertThat(fakeValuesService.fetch("property.dummy")).isEqualTo("x"); - } - - @Test - public void fetchObjectShouldReturnValue() { - assertThat(fakeValuesService.fetchObject("property.dummy")).isEqualTo(Arrays.asList("x", "y", "z")); - } - - @Test - public void safeFetchShouldReturnValueInList() { - doReturn(0).when(randomService).nextInt(Mockito.anyInt()); - assertThat(fakeValuesService.safeFetch("property.dummy", null)).isEqualTo("x"); - } - - @Test - public void safeFetchShouldReturnSimpleList() { - assertThat(fakeValuesService.safeFetch("property.simple", null)).isEqualTo("hello"); - } - - @Test - public void safeFetchShouldReturnEmptyStringWhenPropertyDoesntExist() { - assertThat(fakeValuesService.safeFetch("property.dummy2", "")).isEmpty(); - } - - @Test - public void bothify2Args() { - final DummyService dummy = mock(DummyService.class); - - Faker f = new Faker(); - - String value = fakeValuesService.resolve("property.bothify_2", dummy, f); - assertThat(value).matches("[A-Z]{2}\\d{2}"); - } - - @Test - public void regexifyDirective() { - final DummyService dummy = mock(DummyService.class); - - String value = fakeValuesService.resolve("property.regexify1", dummy, faker); - assertThat(value).isIn("55", "44", "45", "54"); - verify(faker).regexify("[45]{2}"); + public String lastName() { + return "Smith"; } - @Test - public void regexifySlashFormatDirective() { - final DummyService dummy = mock(DummyService.class); - - String value = fakeValuesService.resolve("property.regexify_slash_format", dummy, faker); - assertThat(value).isIn("55", "44", "45", "54"); - verify(faker).regexify("[45]{2}"); - } - - @Test - public void regexifyDirective2() { - final DummyService dummy = mock(DummyService.class); - - String value = fakeValuesService.resolve("property.regexify_cell", dummy, faker); - assertThat(value).isIn("479", "459"); - verify(faker).regexify("4[57]9"); - } - - @Test - public void resolveKeyToPropertyWithAPropertyWithoutAnObject() { - // #{hello} -> DummyService.hello - - // given - final DummyService dummy = mock(DummyService.class); - doReturn("Yo!").when(dummy).hello(); - - // when - final String actual = fakeValuesService.resolve("property.simpleResolution", dummy, faker); - - // then - assertThat(actual).isEqualTo("Yo!"); - verify(dummy).hello(); - verifyNoMoreInteractions(faker); - } - - @Test - public void resolveKeyToPropertyWithAPropertyWithAnObject() { - // given - final Superhero person = mock(Superhero.class); - final DummyService dummy = mock(DummyService.class); - doReturn(person).when(faker).superhero(); - doReturn("Luke Cage").when(person).name(); - - // when - final String actual = fakeValuesService.resolve("property.advancedResolution", dummy, faker); - - // then - assertThat(actual).isEqualTo("Luke Cage"); - verify(faker).superhero(); - verify(person).name(); - } - - @Test - public void resolveKeyToPropertyWithAList() { - // property.resolutionWithList -> #{hello} - // #{hello} -> DummyService.hello - - // given - final DummyService dummy = mock(DummyService.class); - doReturn(0).when(randomService).nextInt(Mockito.anyInt()); - doReturn("Yo!").when(dummy).hello(); - - // when - final String actual = fakeValuesService.resolve("property.resolutionWithList", dummy, faker); - - // then - assertThat(actual).isEqualTo("Yo!"); - verify(dummy).hello(); - } - - @Test - public void resolveKeyWithMultiplePropertiesShouldJoinResults() { - // given - final Superhero person = mock(Superhero.class); - final DummyService dummy = mock(DummyService.class); - doReturn(person).when(faker).superhero(); - - doReturn("Yo Superman!").when(dummy).hello(); - doReturn("up up and away").when(person).descriptor(); - - // when - String actual = fakeValuesService.resolve("property.multipleResolution", dummy, faker); - - // then - assertThat(actual).isEqualTo("Yo Superman! up up and away"); - - verify(faker).superhero(); - verify(person).descriptor(); - verify(dummy).hello(); - } - - @Test - public void testLocaleChain() { - final List chain = fakeValuesService.localeChain(Locale.SIMPLIFIED_CHINESE); - - assertThat(chain).containsExactly(Locale.SIMPLIFIED_CHINESE, Locale.CHINESE, Locale.ENGLISH); - } - - @Test - public void testLocaleChainEnglish() { - final List chain = fakeValuesService.localeChain(Locale.ENGLISH); - - assertThat(chain).containsExactly(Locale.ENGLISH); - } - - @Test - public void testLocaleChainLanguageOnly() { - final List chain = fakeValuesService.localeChain(Locale.CHINESE); - - assertThat(chain).containsExactly(Locale.CHINESE, Locale.ENGLISH); - } - - @Test - public void expressionWithInvalidFakerObject() { - expressionShouldFailWith("#{ObjectNotOnFaker.methodName}", - "Unable to resolve #{ObjectNotOnFaker.methodName} directive."); - } - - @Test - public void expressionWithValidFakerObjectButInvalidMethod() { - expressionShouldFailWith("#{Name.nonExistentMethod}", - "Unable to resolve #{Name.nonExistentMethod} directive."); - } - - /** - * Two things are important here: - * 1) the message in the exception should be USEFUL - * 2) a {@link RuntimeException} should be thrown. - * - * if the message changes, it's ok to update the test provided - * the two conditions above are still true. - */ - @Test - public void expressionWithValidFakerObjectValidMethodInvalidArgs() { - expressionShouldFailWith("#{Number.number_between 'x','y'}", - "Unable to resolve #{Number.number_between 'x','y'} directive."); - } - - @Test - public void futureDateExpression() throws ParseException { - SimpleDateFormat dateFormat = new SimpleDateFormat( "EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH ); - - Date now = new Date(); - Date nowPlus10Days = new Date( now.getTime() + MILLIS_IN_A_DAY * 10 ); - - Date date = dateFormat.parse( fakeValuesService.expression( "#{date.future '10','TimeUnit.DAYS'}", faker )); - - assertThat(date.getTime()).isGreaterThan(now.getTime()); - assertThat(date.getTime()).isLessThan(nowPlus10Days.getTime()); - } - - @Test - public void pastDateExpression() throws ParseException { - SimpleDateFormat dateFormat = new SimpleDateFormat( "EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH ); - - Date now = new Date(); - Date nowMinus5Hours = new Date( now.getTime() - MILLIS_IN_AN_HOUR * 5 ); - - Date date = dateFormat.parse( fakeValuesService.expression( "#{date.past '5','TimeUnit.HOURS'}", faker )); - - assertThat(date.getTime()).isGreaterThan(nowMinus5Hours.getTime()); - assertThat(date.getTime()).isLessThan(now.getTime()); - } - - @Test - public void expressionWithFourArguments() throws ParseException { - - assertThat(fakeValuesService.expression("#{Internet.password '5','8','true','true'}", faker)) - .matches("[\\w\\d\\!%#$@_\\^&\\*]{5,8}"); - } - - /** - * Two things are important here: - * 1) the message in the exception should be USEFUL - * 2) a {@link RuntimeException} should be thrown. - * - * if the message changes, it's ok to update the test provided - * the two conditions above are still true. - */ - @Test - public void expressionCompletelyUnresolvable() { - expressionShouldFailWith("#{x}", "Unable to resolve #{x} directive."); - } - - private void expressionShouldFailWith(String expression, String errorMessage) { - try { - fakeValuesService.expression(expression, faker); - fail("Should have failed with RuntimeException and message of " + errorMessage); - } catch (RuntimeException re) { - assertThat(re.getMessage()).isEqualTo(errorMessage); - } - } - @Test - public void resolveUsingTheSameKeyTwice() { - // #{hello} -> DummyService.hello - - // given - final DummyService dummy = mock(DummyService.class); - when(dummy.hello()).thenReturn("1").thenReturn("2"); - - // when - final String actual = fakeValuesService.resolve("property.sameResolution", dummy, faker); - - // then - assertThat(actual).isEqualTo("1 2"); - verifyNoMoreInteractions(faker); - } - @Test - public void FakeValuesServiceWithNullLocaleTest(){ - try{ - RandomService r=new RandomService(); - FakeValuesService f=new FakeValuesService(null,r); - fail("Should catch IllegalArgumentException"); - }catch (IllegalArgumentException e){ - assertThat(e.getMessage()).isEqualTo("locale is required"); - } - } - public static class DummyService { - public String firstName() { - return "John"; - } - - public String lastName() { - return "Smith"; - } - - public String hello() { - return "Hello"; - } + public String hello() { + return "Hello"; } + } } diff --git a/src/test/java/org/thejavaguy/javafaker/service/FakeValuesTest.java b/src/test/java/org/thejavaguy/javafaker/service/FakeValuesTest.java index 12757e4..dc421b6 100644 --- a/src/test/java/org/thejavaguy/javafaker/service/FakeValuesTest.java +++ b/src/test/java/org/thejavaguy/javafaker/service/FakeValuesTest.java @@ -3,57 +3,54 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.Locale; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; - public class FakeValuesTest { - private static final String PATH = "address"; - private FakeValues fakeValues; - - @BeforeEach - public void before() { - fakeValues = new FakeValues(Locale.ENGLISH, "address.yml", PATH); - } - - @Test - public void supportsPathIsTrueWithTheSameValueAsThePath() { - assertThat(fakeValues.supportsPath(PATH)).isEqualTo(true); - } - - @Test - public void supportsPathIsFalseWhenValueIsNotTheSame() { - assertThat(fakeValues.supportsPath("dog")).isEqualTo(false); - } - - @Test - public void getAValueReturnsAValue() { - assertThat(fakeValues.get(PATH)).isNotNull(); - } - - @Test - public void getAValueDoesNotReturnAValue() { - assertThat(fakeValues.get("dog")).isNull(); - } - - @Test - public void getAValueWithANonEnglishFile() { - FakeValues frenchFakeValues = new FakeValues(Locale.FRENCH); - assertThat(frenchFakeValues.get(PATH)).isNotNull(); - } - - @Test - public void getAValueForHebrewLocale() { - FakeValues hebrew = new FakeValues(new Locale("iw")); - assertThat(hebrew.get(PATH)).isNotNull(); - } - - @Test - public void getAValueFromALocaleThatCantBeLoaded() { - FakeValues fakeValues = new FakeValues(new Locale("nothing")); - assertThat(fakeValues.get(PATH)).isNull(); - } - + private static final String PATH = "address"; + private FakeValues fakeValues; + + @BeforeEach + public void before() { + fakeValues = new FakeValues(Locale.ENGLISH, "address.yml", PATH); + } + + @Test + public void supportsPathIsTrueWithTheSameValueAsThePath() { + assertThat(fakeValues.supportsPath(PATH)).isEqualTo(true); + } + + @Test + public void supportsPathIsFalseWhenValueIsNotTheSame() { + assertThat(fakeValues.supportsPath("dog")).isEqualTo(false); + } + + @Test + public void getAValueReturnsAValue() { + assertThat(fakeValues.get(PATH)).isNotNull(); + } + + @Test + public void getAValueDoesNotReturnAValue() { + assertThat(fakeValues.get("dog")).isNull(); + } + + @Test + public void getAValueWithANonEnglishFile() { + FakeValues frenchFakeValues = new FakeValues(Locale.FRENCH); + assertThat(frenchFakeValues.get(PATH)).isNotNull(); + } + + @Test + public void getAValueForHebrewLocale() { + FakeValues hebrew = new FakeValues(new Locale("iw")); + assertThat(hebrew.get(PATH)).isNotNull(); + } + + @Test + public void getAValueFromALocaleThatCantBeLoaded() { + FakeValues fakeValues = new FakeValues(new Locale("nothing")); + assertThat(fakeValues.get(PATH)).isNull(); + } } diff --git a/src/test/java/org/thejavaguy/javafaker/service/RandomServiceTest.java b/src/test/java/org/thejavaguy/javafaker/service/RandomServiceTest.java index c722347..b12b9e4 100644 --- a/src/test/java/org/thejavaguy/javafaker/service/RandomServiceTest.java +++ b/src/test/java/org/thejavaguy/javafaker/service/RandomServiceTest.java @@ -6,78 +6,76 @@ import java.util.Arrays; import java.util.Collection; import java.util.Random; - import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.thejavaguy.javafaker.AbstractFakerTest; /** * @author pmiklos - * */ public class RandomServiceTest extends AbstractFakerTest { - private RandomService randomService; + private RandomService randomService; - public void initRandomServiceTest(String ignoredTitle, RandomService service) { - this.randomService = service; - } + public void initRandomServiceTest(String ignoredTitle, RandomService service) { + this.randomService = service; + } - public static Collection data() { - Object[][] data = new Object[][]{ - {"RandomService(Random)", new RandomService(new Random())}, - {"RandomService()", new RandomService()} + public static Collection data() { + Object[][] data = + new Object[][] { + {"RandomService(Random)", new RandomService(new Random())}, + {"RandomService()", new RandomService()} }; - return Arrays.asList(data); - } + return Arrays.asList(data); + } - @MethodSource("data") - @ParameterizedTest(name = "Created via {0}") - public void testPositiveBoundariesOnly(String ignoredTitle,RandomService service) { - initRandomServiceTest(ignoredTitle, service); - assertThrows(IllegalArgumentException.class, () -> - randomService.nextLong(0L)); - } + @MethodSource("data") + @ParameterizedTest(name = "Created via {0}") + public void testPositiveBoundariesOnly(String ignoredTitle, RandomService service) { + initRandomServiceTest(ignoredTitle, service); + assertThrows(IllegalArgumentException.class, () -> randomService.nextLong(0L)); + } - @MethodSource("data") - @ParameterizedTest(name = "Created via {0}") - public void testLongWithinBoundary(String ignoredTitle,RandomService service) { - initRandomServiceTest(ignoredTitle, service); - assertThat(randomService.nextLong(1)).isEqualTo(0L); + @MethodSource("data") + @ParameterizedTest(name = "Created via {0}") + public void testLongWithinBoundary(String ignoredTitle, RandomService service) { + initRandomServiceTest(ignoredTitle, service); + assertThat(randomService.nextLong(1)).isEqualTo(0L); - for (int i = 1; i < 10; i++) { - assertThat(randomService.nextLong(2)).isLessThan(2L); - } + for (int i = 1; i < 10; i++) { + assertThat(randomService.nextLong(2)).isLessThan(2L); } + } - @MethodSource("data") - @ParameterizedTest(name = "Created via {0}") - public void testLongMaxBoundary(String ignoredTitle,RandomService service) { - initRandomServiceTest(ignoredTitle, service); - assertThat(randomService.nextLong(Long.MAX_VALUE)).isGreaterThan(0L); - assertThat(randomService.nextLong(Long.MAX_VALUE)).isLessThan(Long.MAX_VALUE); - } + @MethodSource("data") + @ParameterizedTest(name = "Created via {0}") + public void testLongMaxBoundary(String ignoredTitle, RandomService service) { + initRandomServiceTest(ignoredTitle, service); + assertThat(randomService.nextLong(Long.MAX_VALUE)).isGreaterThan(0L); + assertThat(randomService.nextLong(Long.MAX_VALUE)).isLessThan(Long.MAX_VALUE); + } - @MethodSource("data") - @ParameterizedTest(name = "Created via {0}") - public void testIntInRange(String ignoredTitle,RandomService service) { - initRandomServiceTest(ignoredTitle, service); - for (int i = 1; i < 100; i++) { - assertThat(randomService.nextInt(-5, 5)).isGreaterThanOrEqualTo(-5).isLessThanOrEqualTo(5); - } + @MethodSource("data") + @ParameterizedTest(name = "Created via {0}") + public void testIntInRange(String ignoredTitle, RandomService service) { + initRandomServiceTest(ignoredTitle, service); + for (int i = 1; i < 100; i++) { + assertThat(randomService.nextInt(-5, 5)).isGreaterThanOrEqualTo(-5).isLessThanOrEqualTo(5); } + } - @MethodSource("data") - @ParameterizedTest(name = "Created via {0}") - public void testHex(String ignoredTitle,RandomService service) { - initRandomServiceTest(ignoredTitle, service); - assertThat(randomService.hex(8)).matches("^[0-9A-F]{8}$"); - } + @MethodSource("data") + @ParameterizedTest(name = "Created via {0}") + public void testHex(String ignoredTitle, RandomService service) { + initRandomServiceTest(ignoredTitle, service); + assertThat(randomService.hex(8)).matches("^[0-9A-F]{8}$"); + } - @MethodSource("data") - @ParameterizedTest(name = "Created via {0}") - public void testDefaultHex(String ignoredTitle,RandomService service) { - initRandomServiceTest(ignoredTitle, service); - assertThat(randomService.hex()).matches("^[0-9A-F]{8}$"); - } + @MethodSource("data") + @ParameterizedTest(name = "Created via {0}") + public void testDefaultHex(String ignoredTitle, RandomService service) { + initRandomServiceTest(ignoredTitle, service); + assertThat(randomService.hex()).matches("^[0-9A-F]{8}$"); + } }