1
0
mirror of https://github.com/askn/faker.git synced 2023-08-10 21:13:01 +03:00

Compare commits

...

53 Commits
v0.1 ... master

Author SHA1 Message Date
Aşkın Gedik
c8875e3183 Merge branch 'master' of github.com:askn/faker 2022-04-04 21:44:02 +03:00
Aşkın Gedik
99afcf6407 v0.8.0 2022-04-04 21:43:44 +03:00
Aşkın Gedik
979e5b2bc4
Merge pull request #20 from fixtheclouds/code
Added Faker::Code
2022-02-21 13:47:34 +03:00
Egor Romanov
7f32a1197b Added Faker::Code.imei 2022-02-16 22:55:53 +03:00
Egor Romanov
e2c95c114d Added Faker::Code.isbn 2022-02-16 22:53:16 +03:00
Aşkın Gedik
9f8608f7cd v0.7.0 2022-01-17 18:26:28 +03:00
Aşkın Gedik
c1094112ee
Merge pull request #18 from mmacia/master
Added Faker::Date generators for date factories
2022-01-08 23:27:55 +03:00
Moisès Macià
3570ade457 added Faker::Date generators for date factories 2022-01-07 16:35:11 +01:00
robacarp
0d54d8e729
Merge pull request #17 from askn/ci_actions
add github actions CI
2021-04-11 21:49:18 -06:00
Rob
ea898d7352 add github actions CI 2021-04-10 20:42:25 -06:00
Aşkın Gedik
bfda3f2fd8 v0.6.0 2021-04-10 21:03:31 +03:00
Aşkın Gedik
86dcfb72ad
Merge pull request #16 from josacar/master
Support Crystal 1.0 version
2021-04-10 21:02:02 +03:00
Jose Luis Salas
352c3905fc
Support Crystal 1.0 version 2021-03-24 20:13:33 +01:00
Aşkın Gedik
12e5de36f1 v0.5.0 2021-03-18 00:29:58 +03:00
Aşkın Gedik
77ec8b25f3
Merge pull request #15 from jinn999/fix-issue-10-internet-user-name
Fix issue 10 internet user name
2021-03-18 00:13:35 +03:00
Davide Paolo Tua
ffab21cdc5 Remove commented code 2021-02-24 14:47:37 +01:00
Davide Paolo Tua
fa7f556864 Fix username rotating between only 4 fixed values 2021-02-24 14:44:22 +01:00
Aşkın Gedik
112bfd0ba0
Merge pull request #14 from jinn999/fix-failing-business-card-spec
Fix business card failing spec
2020-11-17 22:20:28 +03:00
Davide Paolo Tua
56a48c18bd Fix business card failing spec 2020-11-17 19:15:28 +01:00
Aşkın Gedik
5caaca1080
Merge pull request #13 from josacar/master
Bump version to 0.4.1 to tag it as shards expect
2020-11-07 12:36:24 +03:00
Jose Luis Salas
5b7a1a9e92
Bump version to 0.4.1 to tag it as shards expect 2020-11-01 18:02:03 +01:00
Aşkın Gedik
83c938838b
Merge pull request #7 from rickychilcott/feature/unique
Generate unique address
2019-06-26 21:14:12 +03:00
Ricky Chilcott
06ad8f03e5 Expand Travis script to execute examples 2019-06-19 12:22:22 -04:00
Ricky Chilcott
544bb80025 Clean up comment 2019-06-19 09:32:20 -04:00
Ricky Chilcott
bd1a8efc6c Get all methods to have a unique_ variant 2019-06-19 09:15:51 -04:00
Ricky Chilcott
4d8f2e6f6e Crystal format 2019-06-18 22:20:53 -04:00
Ricky Chilcott
0b8c158403 Merge remote-tracking branch 'askn/master' into feature/unique 2019-06-18 20:53:11 -04:00
Aşkın Gedik
5b53bf19c5
Merge pull request #9 from art-of-dom/travis-fix
Fix nested it in specs
2019-02-28 17:41:10 +03:00
Dom Postorivo
df79923101 fix nested it in specs 2019-02-25 20:55:08 -05:00
Aşkın Gedik
da14470383
Merge pull request #8 from vnbrs/patch-1
Fix README.md titles
2018-12-09 18:15:01 +03:00
Vinicius Brasil
9243265586
Fix README.md titles 2018-12-08 00:30:13 -02:00
Ricky Chilcott
5e4fc757e5 Uniquify no argument methods 2018-09-24 08:22:18 -04:00
Aşkın Gedik
68316d43a1
Merge pull request #6 from rickychilcott/fix/specs
Fix Specs
2018-09-21 16:30:59 +03:00
Ricky Chilcott
6e5e8fad11 Fixing specs 2018-09-21 08:41:48 -04:00
Ricky Chilcott
76edfcec5d Use parse_local because parse requires location to be provided 2018-09-21 08:31:25 -04:00
Ricky Chilcott
c25ae912bf Ignore .DS_Store files 2018-09-21 08:14:13 -04:00
Ricky Chilcott
ed11040aa5 Run crystal tool format 2018-09-21 08:13:42 -04:00
Aşkın Gedik
4176ac1e5d Merge pull request #3 from cazgp/feat/seed
GH-2 Add ability to seed
2017-07-09 23:27:22 +03:00
Caroline Glassberg-Powell
284782b26a GH-2 Add ability to seed
All the random functions are now passed through Faker.rng, a random
number generator that is created by default, but can also be set with
`Faker.seed`.

The tests use all the examples in the README to ensure that everything
has been seeded properly.

The only module not updated is Finance, but that's because the file
itself did not seem to compile, and there weren't any examples of using
it in the README.
2017-07-09 12:44:14 +01:00
Aşkın Gedik
8610498397 Merge branch 'release/0.3.0' 2017-02-23 20:48:31 +03:00
Aşkın Gedik
7b8db5e83d v0.3.0 2017-02-23 20:47:44 +03:00
Aşkın Gedik
ad6ea8dfdb assert => it 2017-02-23 19:48:30 +03:00
Aşkın Gedik
2f5358eb0d add configs for travis 2017-02-18 11:44:25 +03:00
Aşkın Gedik
5fc00a3a6f v0.2.0 2016-10-20 14:35:05 +03:00
Aşkın Gedik
828efc4d56 Merge pull request #1 from sdogruyol/master
Update to Crystal 0.19.4
2016-10-20 11:32:26 +00:00
Serdar Dogruyol
ae84c91f94 Update to Crystal 0.19.4 2016-10-20 14:29:47 +03:00
Aşkın Gedik
fb5c4708f7 commerce 2016-03-28 23:52:01 +03:00
Aşkın Gedik
bc5c00e912 add Address.country_code 2016-03-28 10:41:33 +03:00
Aşkın Gedik
0b5942bf58 update Internet#password 2016-03-28 01:26:33 +03:00
Aşkın Gedik
ca166af7af add Hacker 2016-03-28 00:08:52 +03:00
Aşkın Gedik
ed6663e116 add Number.hexadecimal 2016-03-28 00:08:23 +03:00
Aşkın Gedik
a2b3ede6fa add positive, negative, between 2016-03-27 23:31:10 +03:00
Aşkın Gedik
393096792d update crystal version 2016-03-26 23:42:45 +02:00
40 changed files with 1437 additions and 230 deletions

25
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,25 @@
name: Tests
on:
schedule:
- cron: '0 10 1 * *'
pull_request:
branches:
- master
push:
branches:
- master
jobs:
build:
name: Test
runs-on: ubuntu-latest
container:
image: crystallang/crystal:latest
steps:
- uses: actions/checkout@v2
- run: crystal --version
- run: shards install
- run: crystal spec
- run: crystal run examples/test.cr
- run: crystal run examples/test2.cr

3
.gitignore vendored
View File

@ -2,9 +2,8 @@
/libs/ /libs/
/.crystal/ /.crystal/
/.shards/ /.shards/
.DS_Store
# Libraries don't need dependency lock # Libraries don't need dependency lock
# Dependencies will be locked in application that uses them # Dependencies will be locked in application that uses them
/shard.lock /shard.lock

View File

@ -1 +0,0 @@
language: crystal

View File

@ -1,6 +1,6 @@
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2015 Aşkın Gedik Copyright (c) 2021 Aşkın Gedik
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

105
README.md
View File

@ -1,5 +1,7 @@
# faker # faker
[![Build Status](https://travis-ci.org/askn/faker.svg?branch=master)](https://travis-ci.org/askn/faker)
This shard is a port of [Faker](https://github.com/stympy/faker) gem that generates fake data. This shard is a port of [Faker](https://github.com/stympy/faker) gem that generates fake data.
@ -21,7 +23,11 @@ require "faker"
Faker::Name.name Faker::Name.name
``` ```
### Faker::Address ### Faker.seed
If you wish to seed the random data, you can call `Faker.seed number` and then all subsequent calls will be deterministic.
### Faker::Address
```crystal ```crystal
Faker::Address.city #=> "Imogeneborough" Faker::Address.city #=> "Imogeneborough"
@ -53,12 +59,14 @@ Faker::Address.state_abbr #=> "AP"
Faker::Address.country #=> "French Guiana" Faker::Address.country #=> "French Guiana"
Faker::Address.country_code #=> "IT"
Faker::Address.latitude #=> "-58.17256227443719" Faker::Address.latitude #=> "-58.17256227443719"
Faker::Address.longitude #=> "-156.65548382095133" Faker::Address.longitude #=> "-156.65548382095133"
``` ```
### Faker::Business ### Faker::Business
```crystal ```crystal
@ -71,20 +79,36 @@ Faker::Business.credit_card_type #=> "visa"
``` ```
### Faker::Commerce ### Faker::Code
```crystal
Faker::Code.isbn #=> "640354399-7"
Faker::Code.imei #=> "531691246033652"
```
### Faker::Commerce
```crystal ```crystal
Faker::Commerce.color #=> "lavender" Faker::Commerce.color #=> "lavender"
# Optional arguments max=3, fixed_amount=false
Faker::Commerce.department #=> "Grocery, Health & Beauty" Faker::Commerce.department #=> "Grocery, Health & Beauty"
Faker::Commerce.department(5) #=> "Grocery, Books, Health & Beauty"
Faker::Commerce.department(2, true) #=> "Books & Tools"
Faker::Commerce.product_name #=> "Practical Granite Shirt" Faker::Commerce.product_name #=> "Practical Granite Shirt"
Faker::Commerce.price #=> "44.6" Faker::Commerce.price #=> "44.6"
Faker::Commerce.material #=> "Plastic"
``` ```
### Faker::Company ### Faker::Company
```crystal ```crystal
@ -97,7 +121,25 @@ Faker::Company.logo #=> "https://pigment.github.com/fake-logos/logos/medium/colo
``` ```
### Faker::Internet ### Faker::Date
```crystal
Faker::Date.birthday.to_s("%Y-%m-%d") #=> "1993-03-09"
Faker::Date.between("2020-01-01", "2020-08-15").to_s("%Y-%m-%d") #=> "2020-03-29"
Faker::Date.between_except("2020-01-01", "2020-08-15", "2020-05-10").to_s("%Y-%m-%d") #=> "2020-03-29"
Faker::Date.forward(days: 30).to_s("%Y-%m-%d") #=> "2022-02-09"
Faker::Date.backward(days: 30).to_s("%Y-%m-%d") #=> "2021-12-12"
Faker::Date.in_date_period(year: 2005).to_s("%Y-%m-%d") #=> "2005-02-12"
```
### Faker::Internet
```crystal ```crystal
# Optional argument name=nil # Optional argument name=nil
@ -122,10 +164,16 @@ Faker::Internet.user_name('Nancy') #=> "nancy"
Faker::Internet.user_name('Nancy Johnson', %w(. _ -)) #=> "johnson-nancy" Faker::Internet.user_name('Nancy Johnson', %w(. _ -)) #=> "johnson-nancy"
# Optional argument min_length=0 # Optional arguments: min_length=8, max_length=16
Faker::Internet.password #=> "doloremquealiquidrerum" Faker::Internet.password #=> "vg5msvy1uerg7"
Faker::Internet.password(8) #=> "consecteturadasperiores" Faker::Internet.password(8) #=> "yfgjik0hgzdqs0"
Faker::Internet.password(10, 20) #=> "eoc9shwd1hwq4vbgfw"
Faker::Internet.password(10, 20, true) #=> "3k5qS15aNmG"
Faker::Internet.password(10, 20, true, true) #=> "*%NkOnJsH4"
Faker::Internet.domain_name #=> "effertz.info" Faker::Internet.domain_name #=> "effertz.info"
@ -153,7 +201,7 @@ Faker::Internet.slug('foo bar', '-') #=> "foo-bar"
``` ```
### Faker::Lorem ### Faker::Lorem
```crystal ```crystal
@ -194,7 +242,7 @@ Faker::Lorem.paragraphs(1, true) #=> ""
``` ```
### Faker::Name ### Faker::Name
```crystal ```crystal
Faker::Name.name #=> "Tyshawn Johns Sr." Faker::Name.name #=> "Tyshawn Johns Sr."
@ -211,7 +259,7 @@ Faker::Name.title #=> "Legacy Creative Director"
``` ```
### Faker::Number ### Faker::Number
```crystal ```crystal
@ -223,12 +271,20 @@ Faker::Number.decimal(2) #=> "11.88"
Faker::Number.decimal(2, 3) #=> "18.843" Faker::Number.decimal(2, 3) #=> "18.843"
# Required parameter: digits
Faker::Number.hexadecimal(3) #=> "e74"
Faker::Number.between(1, 10) #=> 7
Faker::Number.positive #=> 235.59238499107653
Faker::Number.negative #=> -4480.042585669558
Faker::Number.digit #=> "1" Faker::Number.digit #=> "1"
``` ```
### Faker::PhoneNumber ### Faker::PhoneNumber
```crystal ```crystal
@ -237,6 +293,31 @@ Faker::PhoneNumber.phone_number #=> "397.693.1309"
``` ```
### Faker::Hacker
---------------------
Are you having trouble writing tech-savvy dialogue for your latest screenplay?
Worry not! Hollywood-grade technical talk is ready to fill out any form where you need to look smart.
```crystal
# Full Phrase
Faker::Hacker.say_something_smart #=> "Try to compress the SQL interface, maybe it will program the back-end hard drive!"
# Short technical abbreviations
Faker::Hacker.abbreviation #=> "RAM"
# Hacker centric adjectives
Faker::Hacker.adjective #=> "open-source"
# Only the best hacker related nouns
Faker::Hacker.noun #=> "bandwidth"
# Actions that hackers take
Faker::Hacker.verb #=> "bypass"
# Verbs that end in -ing
Faker::Hacker.ingverb #=> "synthesizing"
```
### Faker::Team ### Faker::Team
```crystal ```crystal

View File

@ -23,9 +23,15 @@ puts Faker::Address.longitude
puts "\n### Faker::Commerce\n\n" puts "\n### Faker::Commerce\n\n"
puts Faker::Commerce.color puts Faker::Commerce.color
puts Faker::Commerce.unique_color
puts Faker::Commerce.department puts Faker::Commerce.department
puts Faker::Commerce.unique_department
puts Faker::Commerce.unique_department(2)
puts Faker::Commerce.unique_department(2, true)
puts Faker::Commerce.product_name puts Faker::Commerce.product_name
puts Faker::Commerce.price puts Faker::Commerce.price
puts Faker::Commerce.unique_price
puts Faker::Commerce.unique_price(0.0..10_000.00)
puts "\n### Faker::Company\n\n" puts "\n### Faker::Company\n\n"
@ -38,10 +44,16 @@ puts "\n\t### Faker::Internet\n\n"
puts Faker::Internet.email puts Faker::Internet.email
puts Faker::Internet.email("Nancy") puts Faker::Internet.email("Nancy")
puts Faker::Internet.unique_email("Nancy")
puts Faker::Internet.unique_email("Nancy")
puts Faker::Internet.free_email puts Faker::Internet.free_email
puts Faker::Internet.unique_free_email
puts Faker::Internet.free_email("Nancy") puts Faker::Internet.free_email("Nancy")
puts Faker::Internet.unique_free_email("Nancy")
puts Faker::Internet.safe_email puts Faker::Internet.safe_email
puts Faker::Internet.unique_safe_email
puts Faker::Internet.safe_email("Nancy") puts Faker::Internet.safe_email("Nancy")
puts Faker::Internet.unique_safe_email("Nancy")
puts Faker::Internet.user_name puts Faker::Internet.user_name
puts Faker::Internet.user_name("Nancy") puts Faker::Internet.user_name("Nancy")
@ -88,12 +100,25 @@ puts Faker::Name.prefix
puts Faker::Name.suffix puts Faker::Name.suffix
puts Faker::Name.title puts Faker::Name.title
puts "\n\t### Faker::Avatar\n\n"
puts Faker::Avatar.image
puts Faker::Avatar.image("borp")
puts Faker::Avatar.unique_image("borp")
puts Faker::Avatar.unique_image("borp")
puts "\n\t### Faker::Number\n\n" puts "\n\t### Faker::Number\n\n"
puts Faker::Number.number(10) puts Faker::Number.number(10)
# puts Faker::Number.unique_number(10)
# puts Faker::Number.unique_number(10)
# puts Faker::Number.unique_number(10)
puts Faker::Number.decimal(2) puts Faker::Number.decimal(2)
puts Faker::Number.decimal(2, 3) puts Faker::Number.decimal(2, 3)
puts Faker::Number.unique_decimal(2)
# puts Faker::Number.unique_decimal(2, 3)
puts Faker::Number.digit puts Faker::Number.digit
puts Faker::Number.unique_digit
puts "\n\t### Faker::PhoneNumber\n\n" puts "\n\t### Faker::PhoneNumber\n\n"
@ -101,6 +126,10 @@ puts Faker::PhoneNumber.phone_number
puts "\n\t### Faker::Business\n\n" puts "\n\t### Faker::Business\n\n"
p Faker::Business.credit_card_number puts Faker::Business.credit_card_number
p Faker::Business.credit_card_expiry_date puts Faker::Business.credit_card_expiry_date
p Faker::Business.credit_card_type puts Faker::Business.credit_card_type
puts Faker::Business.unique_credit_card_number
puts Faker::Business.unique_credit_card_expiry_date
puts Faker::Business.unique_credit_card_type

213
examples/test2.cr Normal file
View File

@ -0,0 +1,213 @@
require "../src/faker"
p "### Faker::Address"
p Faker::Address.city # => "Imogeneborough"
p Faker::Address.street_name # => "Larkin Fork"
p Faker::Address.street_address # => "282 Kevin Brook"
p Faker::Address.secondary_address # => "Apt. 672"
p Faker::Address.building_number # => "7304"
p Faker::Address.zip_code # => "58517"
p Faker::Address.postcode # => "58517"
p Faker::Address.time_zone # => "Asia/Yakutsk"
p Faker::Address.street_suffix # => "Street"
p Faker::Address.city_suffix # => "fort"
p Faker::Address.city_prefix # => "Lake"
p Faker::Address.state # => "California"
p Faker::Address.state_abbr # => "AP"
p Faker::Address.country # => "French Guiana"
p Faker::Address.latitude # => "-58.17256227443719"
p Faker::Address.longitude # => "-156.65548382095133"
p "### Faker::Business"
p Faker::Business.credit_card_number # => "1228-1221-1221-1431"
p Faker::Business.credit_card_expiry_date # => <Time: 2015-11-11>
p Faker::Business.credit_card_type # => "visa"
p "### Faker::Commerce"
p Faker::Commerce.color # => "lavender"
p Faker::Commerce.department # => "Grocery, Health & Beauty"
p Faker::Commerce.product_name # => "Practical Granite Shirt"
p Faker::Commerce.price # => "44.6"
p "### Faker::Company"
p Faker::Company.name # => "Hirthe-Ritchie"
p Faker::Company.suffix # => "Group"
p Faker::Company.logo # => "https://pigment.github.com/fake-logos/logos/medium/color/5.png"
p "### Faker::Internet"
# Optional argument name=nil
p Faker::Internet.email # => "eliza@mann.net"
p Faker::Internet.email("Nancy") # => "nancy@terry.biz"
# Optional argument name=nil
p Faker::Internet.free_email # => "freddy@gmail.com"
p Faker::Internet.free_email("Nancy") # => "nancy@yahoo.com"
# Optional argument name=nil
p Faker::Internet.safe_email # => "christelle@example.org"
p Faker::Internet.safe_email("Nancy") # => "nancy@example.net"
# Optional arguments specifier=nil, separators=%w(. _)
p Faker::Internet.user_name # => "alexie"
p Faker::Internet.user_name("Nancy") # => "nancy"
p Faker::Internet.user_name("Nancy Johnson", %w(. _ -)) # => "johnson-nancy"
# Optional argument min_length=0
p Faker::Internet.password # => "doloremquealiquidrerum"
p Faker::Internet.password(8) # => "consecteturadasperiores"
p Faker::Internet.domain_name # => "effertz.info"
p Faker::Internet.domain_word # => "haleyziemann"
p Faker::Internet.domain_suffix # => "info"
p Faker::Internet.ip_v4_address # => "24.29.18.175"
p Faker::Internet.ip_v6_address # => "ac5f:d696:3807:1d72:2eb5:4e81:7d2b:e1df"
# Optional argument prefix=""
p Faker::Internet.mac_address # => "e6:0d:00:11:ed:4f"
p Faker::Internet.mac_address("55:44:33") # => "55:44:33:02:1d:9b"
# Optional arguments: host=domain_name, path="/#{user_name}"
p Faker::Internet.url # => "http://thiel.com/chauncey_simonis"
p Faker::Internet.url("example.com") # => "http://example.com/clotilde.swift"
p Faker::Internet.url("example.com", "/foobar.html") # => "http://example.com/foobar.html"
# Optional arguments: words=nil, glue=nil
p Faker::Internet.slug # => "pariatur_laudantium"
p Faker::Internet.slug("foo bar") # => "foo.bar"
p Faker::Internet.slug("foo bar", "-") # => "foo-bar"
p "### Faker::Lorem"
p Faker::Lorem.word # => "repellendus"
# Optional arguments: num=3, supplemental=false
p Faker::Lorem.words # => ["dolores", "adipisci", "nesciunt"]
p Faker::Lorem.words(4) # => ["culpa", "recusandae", "aut", "omnis"]
p Faker::Lorem.words(4, true) # => ["colloco", "qui", "vergo", "deporto"]
# Optional arguments: char_count=255
p Faker::Lorem.characters # => "uw1ep04lhs0c4d931n1jmrspprf5wrj85fefue0y7y6m56b6omquh7br7dhqijwlawejpl765nb1716idmp3xnfo85v349pzy2o9rir23y2qhflwr71c1585fnynguiphkjm8p0vktwitcsm16lny7jzp9t4drwav3qmhz4yjq4k04x14gl6p148hulyqioo72tf8nwrxxcclfypz2lc58lsibgfe5w5p0xv95peafjjmm2frkhdc6duoky0aha"
p Faker::Lorem.characters(10) # => "ang9cbhoa8"
# Optional arguments: word_count=4, supplemental=false, random_words_to_add=6
p Faker::Lorem.sentence # => "Dolore illum animi et neque accusantium."
p Faker::Lorem.sentence(3) # => "Commodi qui minus deserunt sed vero quia."
p Faker::Lorem.sentence(3, true) # => "Inflammatio denego necessitatibus caelestis autus illum."
p Faker::Lorem.sentence(3, false, 4) # => "Aut voluptatem illum fugit ut sit."
p Faker::Lorem.sentence(3, true, 4) # => "Accusantium tantillus dolorem timor."
# Optional arguments: sentence_count=3, supplemental=false
p Faker::Lorem.sentences # => ["Vero earum commodi soluta.", "Quaerat fuga cumque et vero eveniet omnis ut.", "Cumque sit dolor ut est consequuntur."]
p Faker::Lorem.sentences(1) # => ["Ut perspiciatis explicabo possimus doloribus enim quia."]
p Faker::Lorem.sentences(1, true) # => ["Quis capillus curo ager veritatis voro et ipsum."]
# Optional arguments: sentence_count=3, supplemental=false, random_sentences_to_add=3
p Faker::Lorem.paragraph # => "Neque dicta enim quasi. Qui corrupti est quisquam. Facere animi quod aut. Qui nulla consequuntur consectetur sapiente."
p Faker::Lorem.paragraph(2) # => "Illo qui voluptas. Id sit quaerat enim aut cupiditate voluptates dolorum. Porro necessitatibus numquam dolor quia earum."
p Faker::Lorem.paragraph(2, true) # => ""
p Faker::Lorem.paragraph(2, false, 4) # => "Neque aut et nemo aut incidunt voluptates. Dolore cum est sint est. Vitae assumenda porro odio dolores fugiat. Est voluptatum quia rerum."
p Faker::Lorem.paragraph(2, true, 4) # => "Vomito unde uxor annus. Et patior utilis sursum."
# Optional arguments: paragraph_count=3, supplemental=false
p Faker::Lorem.paragraphs # => ""
p Faker::Lorem.paragraphs(1) # => ""
p Faker::Lorem.paragraphs(1, true) # => ""
p "### Faker::Name"
p Faker::Name.name # => "Tyshawn Johns Sr."
p Faker::Name.first_name # => "Kaci"
p Faker::Name.last_name # => "Ernser"
p Faker::Name.prefix # => "Mr."
p Faker::Name.suffix # => "IV"
p Faker::Name.title # => "Legacy Creative Director"
p "### Faker::Number"
# Required parameter: digits
p Faker::Number.number(10) # => "1968353479"
# Required parameter: l_digits
p Faker::Number.decimal(2) # => "11.88"
p Faker::Number.decimal(2, 3) # => "18.843"
p Faker::Number.digit # => "1"
p "### Faker::PhoneNumber"
p Faker::PhoneNumber.phone_number # => "397.693.1309"
p "### Faker::Team"
# Random Team Creature
p Faker::Team.creature # => "gooses"
# Random Team Name created from random US State (Faker::Address.state) prepended to a random Team Creature
p Faker::Team.name # => "Oregon vixens"
# Random Team State
p Faker::Team.state # => "Oregon"
# ---
# Required parameter: digits
p Faker::Number.number(10) # => "1968353479"
# Required parameter: l_digits
p Faker::Number.decimal(2) # => "11.88"
p Faker::Number.decimal(2, 3) # => "18.843"
# Required parameter: digits
p Faker::Number.hexadecimal(3) # => "e74"
p Faker::Number.between(1, 10) # => 7
p Faker::Number.positive # => 235.59238499107653
p Faker::Number.negative # => -4480.042585669558
p Faker::Number.digit # => "1"
p Faker::Address.country_code # => "IT"

View File

@ -1,7 +1,9 @@
name: faker name: faker
version: 0.1.0 version: 0.8.0
authors: authors:
- Aşkın Gedik <askn@bil.omu.edu.tr> - Aşkın Gedik <askn@bil.omu.edu.tr>
license: MIT license: MIT
crystal: "~> 1.0, >= 1.0.0"

35
spec/address_spec.cr Normal file
View File

@ -0,0 +1,35 @@
require "./spec_helper"
describe Faker::Address do
it "should return deterministic results when seeded" do
Faker.seed 123456
Faker::Address.city.should eq "Kemmerland"
Faker::Address.street_name.should eq "Boyer Views"
Faker::Address.street_address.should eq "82059 Batz Passage"
Faker::Address.secondary_address.should eq "Apt. 856"
Faker::Address.building_number.should eq "22820"
Faker::Address.zip_code.should eq "89366"
Faker::Address.postcode.should eq "JA95 9QF"
Faker::Address.time_zone.should eq "Pacific/Honolulu"
Faker::Address.street_suffix.should eq "Loop"
Faker::Address.city_suffix.should eq "mouth"
Faker::Address.city_prefix.should eq "Lake"
Faker::Address.state.should eq "Montana"
Faker::Address.state_abbr.should eq "VA"
Faker::Address.country.should eq "Swaziland"
Faker::Address.country_code.should eq "MK"
Faker::Address.latitude.should eq "-23.850993082533705"
Faker::Address.longitude.should eq "-4.488135572134695"
end
it "should generate unique result" do
Faker.seed 123456
vals = Array(String).new
10_000.times do |t|
vals << Faker::Address.unique_city
end
vals.size.should eq vals.uniq.size
end
end

10
spec/business_spec.cr Normal file
View File

@ -0,0 +1,10 @@
require "./spec_helper"
describe Faker::Business do
it "should return deterministic results when seeded" do
Faker.seed 123456
Faker::Business.credit_card_number.should eq "1228-1221-1221-1431"
Faker::Business.credit_card_expiry_date.should eq Time.local(2013, 9, 12)
Faker::Business.credit_card_type.should eq "mastercard"
end
end

22
spec/code_spec.cr Normal file
View File

@ -0,0 +1,22 @@
require "./spec_helper"
describe Faker::Code do
it "base 10 isbn" do
Faker::Code.isbn.match(/^\d{9}-[\d|X]$/).should_not eq nil
end
it "base 13 isbn" do
Faker::Code.isbn(13).match(/^\d{12}-\d$/).should_not eq nil
end
it "imei" do
Faker::Code.imei.match(/\A[\d.:\-\s]+\z/i).should_not eq nil
end
it "should return deterministic results when seeded" do
Faker.seed 123456
Faker::Code.isbn.should eq "394314441-0"
Faker::Code.isbn(13).should eq "205982563728-9"
Faker::Code.imei.should eq "860839366575918"
end
end

66
spec/commerce_spec.cr Normal file
View File

@ -0,0 +1,66 @@
require "./spec_helper"
describe Faker::Commerce do
it "color" do
Faker::Commerce.color.match(/[a-z]+\.?/).should_not eq nil
end
it "department" do
Faker::Commerce.department.match(/[A-Z][a-z]+\.?/).should_not eq nil
end
it "single_department_should_not_contain_separators" do
Faker::Commerce.department(1).match(/\A[A-Za-z]+\z/).should_not eq nil
end
it "department_should_have_ampersand_as_default_separator" do
Faker::Commerce.department(2, true).scan(" & ").should_not eq nil
end
it "department_should_have_exact_number_of_categories_when_fixed_amount" do
Faker::Commerce.department(10, true).match(/\A([A-Za-z]+, ){8}[A-Za-z]+ & [A-Za-z]+\z/).should_not eq nil
end
it "department_should_never_exceed_the_max_number_of_categories_when_random_amount" do
100.times do
Faker::Commerce.department(6).match(/\A([A-Za-z]+(, | & )){0,5}[A-Za-z]+\z/).should_not eq nil
end
end
it "department_should_have_no_duplicate_categories" do
department = Faker::Commerce.department(10, true)
departments = department.split(/[,& ]+/)
departments.should eq departments.uniq
end
it "product_name" do
Faker::Commerce.product_name.match(/[A-Z][a-z]+\.?/).should_not eq nil
end
it "material" do
Faker::Commerce.material.match(/[A-Z][a-z]+\.?/).should_not eq nil
end
it "price" do
(0 <= Faker::Commerce.price <= 100).should be_true
(5 <= Faker::Commerce.price(5..6) <= 6).should be_true
(990 <= Faker::Commerce.price(990...1000) <= 1000).should be_true
Faker::Commerce.price(5..6).is_a?(Float).should be_true
end
it "price_is_float" do
Faker::Commerce.price.is_a?(Float).should be_true
end
it "should return deterministic results when seeded" do
Faker.seed 123456
Faker::Commerce.color.should eq "fuchsia"
Faker::Commerce.department.should eq "Garden & Tools"
Faker::Commerce.department(5).should eq "Kids, Health, Tools & Music"
Faker::Commerce.department(2, true).should eq "Garden & Industrial"
Faker::Commerce.product_name.should eq "Durable Aluminum Bag"
Faker::Commerce.price.should eq 62.86
Faker::Commerce.material.should eq "Leather"
end
end

View File

@ -5,4 +5,11 @@ describe Faker::Company do
it "logo" do it "logo" do
Faker::Company.logo.match(%r{https://pigment.github.io/fake-logos/logos/medium/color/\d+\.png}).should_not eq nil Faker::Company.logo.match(%r{https://pigment.github.io/fake-logos/logos/medium/color/\d+\.png}).should_not eq nil
end end
it "should return deterministic results when seeded" do
Faker.seed 123456
Faker::Company.name.should eq "Kemmer-Gleichner"
Faker::Company.suffix.should eq "Inc"
Faker::Company.logo.should eq "https://pigment.github.io/fake-logos/logos/medium/color/10.png"
end
end end

106
spec/date_spec.cr Normal file
View File

@ -0,0 +1,106 @@
require "./spec_helper"
describe Faker::Date do
describe "#between" do
it "should return between date" do
from = Time.parse("2019-01-01", "%Y-%m-%d", Time::Location::UTC)
to = Time.parse("2022-01-01", "%Y-%m-%d", Time::Location::UTC)
100.times do
random_date = Faker::Date.between(from: from, to: to)
random_date.should be >= from
random_date.should be <= to
end
end
it "should raise and exception on invalid date" do
from = "2019-01-01"
to = "0000-00-00"
expect_raises(ArgumentError, "Invalid time") do
Faker::Date.between(from: from, to: to)
end
end
end
describe "#between_except" do
it "should return between date except gvien one" do
from = "2012-01-01"
to = "2012-01-05"
excepted = "2012-01-03"
100.times do
random_date = Faker::Date.between_except(from: from, to: to, excepted: excepted)
random_date.should_not be_nil
random_date.should_not eq(Time.parse(excepted, "%Y-%m-%d", Time::Location::UTC))
end
end
it "should raise an excpetion when all args are the same" do
from = "2012-01-01"
to = "2012-01-01"
excepted = "2012-01-01"
expect_raises(ArgumentError, "From date, to date and excepted date must not be the same") do
Faker::Date.between_except(from: from, to: to, excepted: excepted)
end
end
end
describe "#birthday" do
it "should return a birthday" do
min = 40
max = 90
t = Time.utc
birthday_min = Time.utc(t.year - max, t.month, t.day)
birthday_max = Time.utc(t.year - min, t.month, t.day)
100.times do
birthday = Faker::Date.birthday(min_age: min, max_age: max)
birthday.should be >= birthday_min
birthday.should be <= birthday_max
end
end
it "should return today when min_age and max_age are the same" do
min = 0
max = 0
t = Time.utc
birthday = Faker::Date.birthday(min_age: min, max_age: max)
birthday.should eq Time.utc(t.year, t.month, t.day)
end
end
it "should return a forward date" do
today = Time.utc
100.times do
random_date = Faker::Date.forward(days: 5)
random_date.should be > today
end
end
it "should return a backward date" do
today = Time.utc
100.times do
random_date = Faker::Date.backward(days: 5)
random_date.should be < today
end
end
describe "#date_in_period" do
it "should work with default params" do
current_year = Time.utc.year
10.times do
date = Faker::Date.in_date_period
date.year.should eq(current_year)
end
end
end
end

42
spec/hacker_spec.cr Normal file
View File

@ -0,0 +1,42 @@
require "./spec_helper"
describe Faker::Hacker do
it { (Faker::Hacker.phrases.size == 8).should be_true }
it "phrases" do
Faker::Hacker.phrases.each do |phrase|
phrase.nil?.should be_false
(phrase == "").should be_false
end
end
it "noun" do
Faker::Hacker.noun.match(/\w+/).should_not eq nil
end
it "abbreviation" do
Faker::Hacker.abbreviation.match(/\w+/).should_not eq nil
end
it "adjective" do
Faker::Hacker.adjective.match(/\w+/).should_not eq nil
end
it "verb" do
Faker::Hacker.verb.match(/\w+/).should_not eq nil
end
it "ingverb" do
Faker::Hacker.ingverb.match(/\w+/).should_not eq nil
end
it "should return deterministic results when seeded" do
Faker.seed 123456
Faker::Hacker.say_something_smart.should eq "backing up the transmitter won't do anything, we need to bypass the optical RSS firewall!"
Faker::Hacker.abbreviation.should eq "USB"
Faker::Hacker.adjective.should eq "virtual"
Faker::Hacker.noun.should eq "port"
Faker::Hacker.verb.should eq "transmit"
Faker::Hacker.ingverb.should eq "calculating"
end
end

View File

@ -23,7 +23,7 @@ describe Faker::Internet do
it "user_name_with_integer_arg" do it "user_name_with_integer_arg" do
(1..32).to_a.each do |min_length| (1..32).to_a.each do |min_length|
assert { Faker::Internet.user_name(min_length).size >= min_length } (Faker::Internet.user_name(min_length).size >= min_length).should be_true
end end
end end
@ -31,8 +31,8 @@ describe Faker::Internet do
(1..32).to_a.each do |min_length| (1..32).to_a.each do |min_length|
(min_length..32).each do |max_length| (min_length..32).each do |max_length|
l = Faker::Internet.user_name((min_length..max_length)).size l = Faker::Internet.user_name((min_length..max_length)).size
assert { l >= min_length } (l >= min_length).should be_true
assert { l <= max_length } (l <= max_length).should be_true
end end
end end
end end
@ -41,8 +41,8 @@ describe Faker::Internet do
(1..32).to_a.each do |min_length| (1..32).to_a.each do |min_length|
(min_length + 1..33).each do |max_length| (min_length + 1..33).each do |max_length|
l = Faker::Internet.user_name((min_length...max_length)).size l = Faker::Internet.user_name((min_length...max_length)).size
assert { l >= min_length } (l >= min_length).should be_true
assert { l <= max_length - 1 } (l <= max_length - 1).should be_true
end end
end end
end end
@ -51,8 +51,8 @@ describe Faker::Internet do
(1..32).to_a.each do |min_length| (1..32).to_a.each do |min_length|
(min_length + 1..33).each do |max_length| (min_length + 1..33).each do |max_length|
u = Faker::Internet.user_name((min_length...max_length), %w(=)) u = Faker::Internet.user_name((min_length...max_length), %w(=))
assert { u.size.between? min_length, max_length - 1 } (min_length <= u.size <= max_length - 1).should be_true
assert { u.match(/\A[a-z]+((=)?[a-z]*)*\z/) } u.match(/\A[a-z]+((=)?[a-z]*)*\z/).should_not eq nil
end end
end end
end end
@ -62,32 +62,32 @@ describe Faker::Internet do
end end
it "password_with_integer_arg" do it "password_with_integer_arg" do
# (1..32).to_a.each do |min_length| (1..32).to_a.each do |min_length|
# assert { Faker::Internet.password(min_length).size >= min_length } (Faker::Internet.password(min_length).size >= min_length).should be_true
# end end
end end
it "password_max_with_integer_arg" do it "password_max_with_integer_arg" do
# (1..32).to_a.each do |min_length| (1..32).to_a.each do |min_length|
# max_length = min_length + 4 max_length = min_length + 4
# assert { Faker::Internet.password(min_length, max_length).size <= max_length } (Faker::Internet.password(min_length, max_length).size <= max_length).should be_true
# end end
end end
it "password_with_mixed_case" do it "password_with_mixed_case" do
assert { Faker::Internet.password.match(/[A-Z]+/) } Faker::Internet.password.match(/[A-Z]+/).should_not eq nil
end end
it "password_without_mixed_case" do it "password_without_mixed_case" do
# Faker::Internet.password(8, 12, false).match(/[^A-Z]+/).should_not eq nil Faker::Internet.password(8, 12, false).match(/[^A-Z]+/).should_not eq nil
end end
it "password_with_special_chars" do it "password_with_special_chars" do
# Faker::Internet.password(8, 12, true, true).match(/[!@#\$%\^&\*]+/).should_not eq nil Faker::Internet.password(8, 12, true, true).match(/[!@#\$%\^&\*]+/).should_not eq nil
end end
it "password_without_special_chars" do it "password_without_special_chars" do
# Faker::Internet.password(8, 12, true).match(/[^!@#\$%\^&\*]+/).should_not eq nil Faker::Internet.password(8, 12, true).match(/[^!@#\$%\^&\*]+/).should_not eq nil
end end
it "domain_name" do it "domain_name" do
@ -106,7 +106,7 @@ describe Faker::Internet do
Faker::Internet.ip_v4_address.count('.').should eq 3 Faker::Internet.ip_v4_address.count('.').should eq 3
100.times do 100.times do
assert { Faker::Internet.ip_v4_address.split(".").map { |octet| octet.to_i }.max <= 255 } (Faker::Internet.ip_v4_address.split(".").map { |octet| octet.to_i }.max <= 255).should be_true
end end
end end
@ -119,11 +119,11 @@ describe Faker::Internet do
1000.times do 1000.times do
# address = Faker::Internet.public_ip_v4_address # address = Faker::Internet.public_ip_v4_address
# assert_not_match ten_dot, address # it_not_match ten_dot, address
# assert_not_match one_two_seven, address # it_not_match one_two_seven, address
# assert_not_match one_six_nine, address # it_not_match one_six_nine, address
# assert_not_match one_nine_two, address # it_not_match one_nine_two, address
# assert_not_match one_seven_two, address # it_not_match one_seven_two, address
end end
end end
@ -132,18 +132,18 @@ describe Faker::Internet do
Faker::Internet.mac_address("").count(":").should eq 5 Faker::Internet.mac_address("").count(":").should eq 5
100.times do 100.times do
assert { Faker::Internet.mac_address.split(":").map { |d| d.to_i(16) }.max <= 255 } (Faker::Internet.mac_address.split(":").map { |d| d.to_i(16) }.max <= 255).should be_true
end end
assert { Faker::Internet.mac_address("fa:fa:fa").starts_with?("fa:fa:fa") } (Faker::Internet.mac_address("fa:fa:fa").starts_with?("fa:fa:fa")).should be_true
assert { Faker::Internet.mac_address("01:02").starts_with?("01:02") } (Faker::Internet.mac_address("01:02").starts_with?("01:02")).should be_true
end end
it "ip_v6_address" do it "ip_v6_address" do
Faker::Internet.ip_v6_address.count(":").should eq 7 Faker::Internet.ip_v6_address.count(":").should eq 7
100.times do 100.times do
# assert { Faker::Internet.ip_v6_address.split(".").map { |h| "0x#{h}".to_i }.max <= 65535 } # it { Faker::Internet.ip_v6_address.split(".").map { |h| "0x#{h}".to_i }.max <= 65535 }
end end
end end
@ -166,4 +166,35 @@ describe Faker::Internet do
it "device_token" do it "device_token" do
# Faker::Internet.device_token.size.should eq 64 # Faker::Internet.device_token.size.should eq 64
end end
it "should return deterministic results when seeded" do
Faker.seed 123456
Faker::Internet.email.should eq "danyka.gleichner@fay.net"
Faker::Internet.email("Nancy").should eq "nancy@barrows.name"
Faker::Internet.free_email.should eq "dayne_brown@hotmail.com"
Faker::Internet.free_email("Nancy").should eq "nancy@yahoo.com"
Faker::Internet.safe_email.should eq "cassie@example.net"
Faker::Internet.safe_email("Nancy").should eq "nancy@example.org"
Faker::Internet.user_name.should eq "eve_batz"
Faker::Internet.user_name("Nancy").should eq "nancy"
Faker::Internet.user_name("Nancy Johnson", [".", "_", "-"] of ::String).should eq "nancy-johnson"
Faker::Internet.password.should eq "P2AtB7Vm"
Faker::Internet.password(8).should eq "XzKdXc0qG"
Faker::Internet.password(10, 20).should eq "Vj9gVt6lDlQ"
Faker::Internet.password(10, 20, true).should eq "7c2s0zXmQlT"
Faker::Internet.password(10, 20, true, true).should eq "@6IpGuR8PvG"
Faker::Internet.domain_name.should eq "beatty.io"
Faker::Internet.domain_word.should eq "veum"
Faker::Internet.domain_suffix.should eq "io"
Faker::Internet.ip_v4_address.should eq "230.101.43.38"
Faker::Internet.ip_v6_address.should eq "a970:ba8b:26b8:f682:cc5a:cb38:94d3:7911"
Faker::Internet.mac_address.should eq "00:68:df:77:d0:57"
Faker::Internet.mac_address("55:44:33").should eq "55:44:33:d9:d8:d5"
Faker::Internet.url.should eq "http://raugottlieb.com/mia_hills"
Faker::Internet.url("example.com").should eq "http://example.com/daron_nolan"
Faker::Internet.url("example.com", "/foobar.html").should eq "http://example.com/foobar.html"
Faker::Internet.slug.should eq "doloribus_quidem"
Faker::Internet.slug("foo bar").should eq "foo_bar"
Faker::Internet.slug("foo bar", "-").should eq "foo-bar"
end
end end

29
spec/lorem_spec.cr Normal file
View File

@ -0,0 +1,29 @@
require "./spec_helper"
describe Faker::Lorem do
it "should return deterministic results when seeded" do
Faker.seed 123456
Faker::Lorem.word.should eq "consequatur"
Faker::Lorem.words.should eq ["porro", "eos", "velit"]
Faker::Lorem.words(4).should eq ["illo", "omnis", "quam", "quia"]
Faker::Lorem.words(4, true).should eq ["abstergo", "volo", "congregatio", "cenaculum"]
Faker::Lorem.characters.should eq "rtu4oasce8rh8v9boy4o7dvw9da4ehtukyicl07az92gxkatlehuga41fqg8v06po1txnjcylbivmv5z9rcgg0hizegu4lck3rnja8kvpwiwp4lds3au07h9lk3k3y7a1c5ec2jtlo5zjtcm3blh6zgtk9rq8wpkqszhv0tstyydx8974aik0j2nkck9ve4kjmh0gn9als5wwxjwtot2yegk8jwe8plvbffu86w38abdq4cupnu4tig75lmu82g"
Faker::Lorem.characters(10).should eq "qunro8qzs5"
Faker::Lorem.sentence.should eq "Dicta laudantium aut aut et asperiores quidem accusamus impedit."
Faker::Lorem.sentence(3).should eq "Quam eum fugit."
Faker::Lorem.sentence(3, true).should eq "Caelum arma illum depopulo cupressus quaerat suus."
Faker::Lorem.sentence(3, false, 4).should eq "Est non necessitatibus."
Faker::Lorem.sentence(3, true, 4).should eq "Accedo venustas summisse cito sperno."
Faker::Lorem.sentences.should eq ["Voluptatem similique quia architecto quo.", "Culpa fugiat pariatur facilis ea accusantium voluptatem consequatur.", "Similique quis velit excepturi quia."]
Faker::Lorem.sentences(1).should eq ["Tempore repellat omnis."]
Faker::Lorem.sentences(1, true).should eq ["Aedificium adhuc patruus capio valens molestiae sit."]
Faker::Lorem.paragraph.should eq "Fugit repellendus suscipit dolores. Voluptatem adipisci nihil cupiditate quisquam ad. Est repellat consequuntur laboriosam reiciendis est sit. Vel molestiae ipsam."
Faker::Lorem.paragraph(2).should eq "Non consectetur itaque aut voluptas cumque est numquam. Non impedit quaerat iusto consequatur tempora nemo amet."
Faker::Lorem.paragraph(2, true).should eq "Pecus urbs curo vinitor volubilis. Coadunatio tunc quas compono. Vetus ascit adfectus civis minus tristis adulatio solio."
Faker::Lorem.paragraph(2, false, 4).should eq "Minima ducimus officia reprehenderit dolorem. Labore quia ut asperiores eos excepturi. Quibusdam tempore incidunt sunt quaerat provident."
Faker::Lorem.paragraph(2, true, 4).should eq "Tego vinco ultio celebrer eveniet cupio argentum speculum. Candidus arbor quibusdam angulus termes. Strenuus concido vulnero. Desino assentator deludo stabilis vallum autem demergo. Temeritas tristis nihil aperio acerbitas."
Faker::Lorem.paragraphs.should eq ["Voluptatem id dolor tempora. Praesentium harum dolores et explicabo unde ut. Sit deleniti vel ullam enim neque non itaque. Rerum qui quam quis et voluptate. Modi tenetur eius molestiae.", "Eaque pariatur quasi optio aliquam nihil quibusdam inventore. Voluptas eaque est nesciunt tenetur vel. Accusamus et et.", "Distinctio cum deserunt quia natus eos debitis neque. Qui voluptates quisquam. Facilis voluptatem et. Nihil nostrum occaecati at."]
Faker::Lorem.paragraphs(1).should eq ["Libero voluptatem neque et autem aspernatur earum animi. Ut iure sed quo quasi dolores aut. Voluptas possimus voluptatem nisi."]
Faker::Lorem.paragraphs(1, true).should eq ["Cibo cognatus temporibus demulceo cinis. Voluptatibus vobis ver cursus aperiam sulum apostolus. Id animadverto caste. Summisse derideo vallum. Suspendo et denuo collum accendo tamisium verecundia iste."]
end
end

13
spec/name_spec.cr Normal file
View File

@ -0,0 +1,13 @@
require "./spec_helper"
describe Faker::Name do
it "should return deterministic results when seeded" do
Faker.seed 123456
Faker::Name.name.should eq "Danyka Gleichner DDS"
Faker::Name.first_name.should eq "Molly"
Faker::Name.last_name.should eq "Fay"
Faker::Name.prefix.should eq "Dr."
Faker::Name.suffix.should eq "DDS"
Faker::Name.title.should eq "Direct Markets Associate"
end
end

79
spec/number_spec.cr Normal file
View File

@ -0,0 +1,79 @@
require "./spec_helper"
describe Faker::Number do
it "number" do
Faker::Number.number(10).match(/[0-9]{10}/).should_not eq nil
10.times do |digits|
digits += 1
Faker::Number.number(digits).match(/^[0-9]{#{digits}}$/).should_not eq nil
end
end
it "decimal" do
Faker::Number.decimal(2).match(/[0-9]{2}\.[0-9]{2}/).should_not eq nil
Faker::Number.decimal(4, 5).match(/[0-9]{4}\.[0-9]{5}/).should_not eq nil
end
it "digit" do
Faker::Number.digit.match(/[0-9]{1}/).should_not eq nil
end
it "between" do
100.times do
random_number = Faker::Number.between(-50, 50)
(random_number >= -50).should eq true
(random_number <= 50).should eq true
end
end
it "positive" do
100.times do
random_number = Faker::Number.positive(1, 100)
(random_number >= 1).should be_true
(random_number <= 100).should be_true
end
end
it "negative" do
100.times do
random_number = Faker::Number.negative(-1, -100)
(random_number <= -1).should be_true
(random_number >= -100).should be_true
end
end
it "force_positive" do
random_number = Faker::Number.positive(-1, -100)
(random_number >= 1).should be_true
(random_number <= 100).should be_true
end
it "force_negative" do
random_number = Faker::Number.negative(1, 100)
(random_number <= -1).should be_true
(random_number >= -100).should be_true
end
it "parameters_order" do
random_number = Faker::Number.between(100, 1)
(random_number >= 1).should be_true
(random_number <= 100).should be_true
end
it "hexadecimal" do
Faker::Number.hexadecimal(4).match(/[0-9a-f]{4}/).should_not eq nil
Faker::Number.hexadecimal(7).match(/[0-9a-f]{7}/).should_not eq nil
end
it "should return deterministic results when seeded" do
Faker.seed 123456
Faker::Number.number(10).should eq "9394314441"
Faker::Number.decimal(2).should eq "12.05"
Faker::Number.decimal(2, 3).should eq "98.256"
Faker::Number.hexadecimal(3).should eq "37c"
Faker::Number.between(1, 10).should eq 9
Faker::Number.positive.should eq 352.4124353316201
Faker::Number.negative.should eq -4363.992315679857
Faker::Number.digit.should eq "9"
end
end

View File

@ -0,0 +1,8 @@
require "./spec_helper"
describe Faker::PhoneNumber do
it "should return deterministic results when seeded" do
Faker.seed 123456
Faker::PhoneNumber.phone_number.should eq "894.314.4411 x20598"
end
end

View File

@ -16,4 +16,11 @@ describe Faker::Team do
it "sport" do it "sport" do
# Faker::Team.sport.match(/(\w+){1}/).should_not eq nil # Faker::Team.sport.match(/(\w+){1}/).should_not eq nil
end end
it "should return deterministic results when seeded" do
Faker.seed 123456
Faker::Team.creature.should eq "vampires"
Faker::Team.name.should eq "New Jersey griffins"
Faker::Team.state.should eq "Arkansas"
end
end end

File diff suppressed because one or more lines are too long

View File

@ -1,14 +1,21 @@
require "./data.cr" require "./data.cr"
require "./faker/base"
require "./faker/*" require "./faker/*"
module Faker module Faker
class_getter rng : Random = Random.new
def self.seed(number)
@@rng = Random.new number
end
def self.numerify(number_string) def self.numerify(number_string)
number_string = number_string as String number_string = number_string.as String
number_string.sub(/#/) { (rand(9) + 1).to_s }.gsub(/#/) { rand(10).to_s } number_string.sub(/#/) { (@@rng.rand(9) + 1).to_s }.gsub(/#/) { @@rng.rand(10).to_s }
end end
def self.letterify(letter_string) def self.letterify(letter_string)
letter_string.gsub(/\?/) { ("A".."Z").to_a.sample } letter_string.gsub(/\?/) { ("A".."Z").to_a.sample(@@rng) }
end end
def self.bothify(string) def self.bothify(string)
@ -17,26 +24,26 @@ module Faker
def self.regexify(re) def self.regexify(re)
re = re.source if re.is_a?(Regex) re = re.source if re.is_a?(Regex)
re.gsub(/^\/?\^?/, "").gsub(/\$?\/?$/, "") # Ditch the anchors re.gsub(/^\/?\^?/, "").gsub(/\$?\/?$/, "") # Ditch the anchors
.gsub(/\{(\d+)\}/) { "{#{$1},#{$1}}" }.gsub(/\?/, "{0,1}") # All {2} become {2,2} and ? become {0,1} .gsub(/\{(\d+)\}/) { "{#{$1},#{$1}}" }.gsub(/\?/, "{0,1}") # All {2} become {2,2} and ? become {0,1}
.gsub(/(\[[^\]]+\])\{(\d+),(\d+)\}/) { |match| $1 * (Range.new($2.to_i, $3.to_i)).to_a.sample } # [12]{1,2} becomes [12] or [12][12] .gsub(/(\[[^\]]+\])\{(\d+),(\d+)\}/) { |match| $1 * (Range.new($2.to_i, $3.to_i)).to_a.sample(@@rng) } # [12]{1,2} becomes [12] or [12][12]
.gsub(/(\([^\)]+\))\{(\d+),(\d+)\}/) { |match| $1 * ($2.to_i..$3.to_i).to_a.sample } # (12|34){1,2} becomes (12|34) or (12|34)(12|34) .gsub(/(\([^\)]+\))\{(\d+),(\d+)\}/) { |match| $1 * ($2.to_i..$3.to_i).to_a.sample(@@rng) } # (12|34){1,2} becomes (12|34) or (12|34)(12|34)
.gsub(/(\\?.)\{(\d+),(\d+)\}/) { |match| $1 * ($2.to_i..$3.to_i).to_a.sample } # A{1,2} becomes A or AA or \d{3} becomes \d\d\d .gsub(/(\\?.)\{(\d+),(\d+)\}/) { |match| $1 * ($2.to_i..$3.to_i).to_a.sample(@@rng) } # A{1,2} becomes A or AA or \d{3} becomes \d\d\d
.gsub(/\((.*?)\)/) { |match| match.gsub(/[\(\)]/, "").split("|").sample } # (this|that) becomes "this" or "that" .gsub(/\((.*?)\)/) { |match| match.gsub(/[\(\)]/, "").split("|").sample(@@rng) } # (this|that) becomes "this" or "that"
.gsub(/\[([^\]]+)\]/) { |match| match.gsub(/(\w\-\w)/) { |range| ((0...range.size).map { |i| range[i].to_s }).join("").split("-").to_a.sample } } # All A-Z inside of [] become C (or X, or whatever) .gsub(/\[([^\]]+)\]/) { |match| match.gsub(/(\w\-\w)/) { |range| ((0...range.size).map { |i| range[i].to_s }).join("").split("-").to_a.sample(@@rng) } } # All A-Z inside of [] become C (or X, or whatever)
.gsub(/\[([^\]]+)\]/) { |match| $1.split("").sample } # All [ABC] become B (or A or C) .gsub(/\[([^\]]+)\]/) { |match| $1.split("").sample(@@rng) } # All [ABC] become B (or A or C)
.gsub("\\d") { |match| (0..9).to_a.sample } .gsub("\\d") { |match| (0..9).to_a.sample(@@rng) }
.gsub("\\w") { |match| (("A".."Z").to_a + (0..9).to_a).sample } .gsub("\\w") { |match| (("A".."Z").to_a + (0..9).to_a).sample(@@rng) }
end end
def self.fetch(data) def self.fetch(data)
data = data as Array data = data.as Array
fetched = data.sample as String fetched = data.sample(@@rng).as String
if fetched.match(/^\//) && fetched.match(/\/$/) # A regex if fetched.match(/^\//) && fetched.match(/\/$/) # A regex
fetched = Faker.regexify(fetched) fetched = Faker.regexify(fetched)
end end
Faker.parse(fetched) as String Faker.parse(fetched).as String
end end
def self.parse(st) def self.parse(st)
@ -55,6 +62,7 @@ module Faker
Name.name, Name.name,
Name.prefix, Name.prefix,
Name.suffix, Name.suffix,
Team.creature,
], $1) ], $1)
end end
end end
@ -69,4 +77,10 @@ module Faker
"Hoaydaaa" "Hoaydaaa"
end end
end end
# Generates a random value between the interval
def self.rand_in_range(from, to)
from, to = to, from if to < from
@@rng.rand(from..to)
end
end end

View File

@ -1,26 +1,33 @@
module Faker module Faker
class Address class Address < Base
def self.zip_code def self.zip_code
Faker.numerify(["#####", "#####-####"].sample) Faker.numerify(["#####", "#####-####"].sample(Faker.rng))
end end
{% for data_type in %w(state state_abbr city_suffix city_prefix country street_suffix) %} uniquify_builder(zip_code)
{% for data_type in %w(state state_abbr city_suffix city_prefix country street_suffix country_code) %}
def self.{{data_type.id}} def self.{{data_type.id}}
Faker.fetch(Data["address"]["{{data_type.id}}"]) Faker.fetch(Data["address"]["{{data_type.id}}"])
end end
uniquify_builder({{data_type.id}})
{% end %} {% end %}
def self.city def self.city
Faker.fetch(Data["address"]["city"]) Faker.fetch(Data["address"]["city"])
end end
uniquify_builder(city)
def self.street_name def self.street_name
[ [
->{ [Name.last_name, street_suffix].join(" ") }, ->{ [Name.last_name, street_suffix].join(" ") },
->{ [Name.first_name, street_suffix].join(" ") }, ->{ [Name.first_name, street_suffix].join(" ") },
].sample.call ].sample(Faker.rng).call
end end
uniquify_builder(street_name)
def self.street_address def self.street_address
Faker.numerify([ Faker.numerify([
->{ "##### %s" % street_name }, ->{ "##### %s" % street_name },
@ -29,34 +36,48 @@ module Faker
->{ "##### %s" % street_name }, ->{ "##### %s" % street_name },
->{ "##### %s Apt. ###" % street_name }, ->{ "##### %s Apt. ###" % street_name },
->{ "##### %s Suite ###" % street_name }, ->{ "##### %s Suite ###" % street_name },
].sample.call) ].sample(Faker.rng).call)
end end
uniquify_builder(street_address)
def self.secondary_address def self.secondary_address
Faker.numerify(Faker.fetch(Data["address"]["secondary_address"])) Faker.numerify(Faker.fetch(Data["address"]["secondary_address"]))
end end
uniquify_builder(street_address)
def self.building_number def self.building_number
Faker.bothify(Faker.fetch(Data["address"]["building_number"])) Faker.bothify(Faker.fetch(Data["address"]["building_number"]))
end end
uniquify_builder(building_number)
def self.postcode def self.postcode
Faker.bothify([ Faker.bothify([
->{ "??# #??" }, ->{ "??# #??" },
->{ "??## #??" }, ->{ "??## #??" },
].sample.call) ].sample(Faker.rng).call)
end end
uniquify_builder(postcode)
def self.latitude def self.latitude
((rand * 180) - 90).to_s ((Faker.rng.rand * 180) - 90).to_s
end end
uniquify_builder(latitude)
def self.longitude def self.longitude
((rand * 360) - 180).to_s ((Faker.rng.rand * 360) - 180).to_s
end end
uniquify_builder(longitude)
def self.time_zone def self.time_zone
Faker.bothify(Faker.fetch(Data["address"]["time_zone"])) Faker.fetch(Data["address"]["time_zone"])
end end
uniquify_builder(time_zone)
end end
end end

View File

@ -1,8 +1,10 @@
module Faker module Faker
class Avatar class Avatar < Base
def self.image(slug = nil) def self.image(slug = nil)
slug ||= Faker::Lorem.word slug ||= Faker::Lorem.word
"http://robohash.org/#{slug}" "http://robohash.org/#{slug}"
end end
uniquify_builder(image, slug = nil)
end end
end end

25
src/faker/base.cr Normal file
View File

@ -0,0 +1,25 @@
module Faker
class NonUniqueValue < Exception
end
class Base
alias Any = String | Int32 | Float64 | Time
macro uniquify_builder(attribute_name, *modified_method_attributes)
@@__unique_vals_for_{{attribute_name}} = Array(Any).new
def self.unique_{{attribute_name}}({% if !modified_method_attributes.empty? %}{{*modified_method_attributes}},{% end %} max_retries = 10_0000)
max_retries.times do |t|
val = self.{{attribute_name}}({{*modified_method_attributes}})
if !@@__unique_vals_for_{{attribute_name}}.includes?(val)
@@__unique_vals_for_{{attribute_name}} << val
return val
end
end
raise NonUniqueValue.new("Unable to generate unique value for {{attribute_name}}")
end
end
end
end

View File

@ -1,16 +1,22 @@
module Faker module Faker
class Business class Business < Base
def self.credit_card_number def self.credit_card_number
Faker.fetch(Data["business"]["credit_card_numbers"]) Faker.fetch(Data["business"]["credit_card_numbers"])
end end
uniquify_builder(credit_card_number)
def self.credit_card_expiry_date def self.credit_card_expiry_date
credit_card_expiry_date = Faker.fetch(Data["business"]["credit_card_expiry_dates"]) as String credit_card_expiry_date = Faker.fetch(Data["business"]["credit_card_expiry_dates"]).as String
Time.parse(credit_card_expiry_date, "%Y-%m-%d") Time.parse_local(credit_card_expiry_date, "%Y-%m-%d")
end end
uniquify_builder(credit_card_expiry_date)
def self.credit_card_type def self.credit_card_type
Faker.fetch(Data["business"]["credit_card_types"]) Faker.fetch(Data["business"]["credit_card_types"])
end end
uniquify_builder(credit_card_type)
end end
end end

66
src/faker/code.cr Normal file
View File

@ -0,0 +1,66 @@
module Faker
class Code < Base
RBI = %w[01 10 30 33 35 44 45 49 50 51 52 53 54 86 91 98 99]
def self.isbn(base : Int32 = 10)
case base
when 10 then generate_base10_isbn
when 13 then generate_base13_isbn
else raise ArgumentError.new("base must be 10 or 13")
end
end
def self.imei
str = Array.new(15, 0)
sum = 0
len = 15
# Fill in the first two values of the string based with the specified prefix.
arr = RBI.sample(Faker.rng)
str[0] = arr[0].to_i
str[1] = arr[1].to_i
pos = 2
# Fill all the remaining numbers except for the last one with random values.
while pos < (len - 1)
str[pos] = Faker.rng.rand(0..9)
pos += 1
end
# Calculate the Luhn checksum of the values thus far
len_offset = (len + 1) % 2
(0..(len - 1)).each do |position|
if (position + len_offset).odd?
t = str[position] * 2
t -= 9 if t > 9
sum += t
else
sum += str[position]
end
end
str[len - 1] = (10 - (sum % 10)) % 10
str.join("")
end
private def self.generate_base10_isbn
values = Faker.regexify(/\d{9}/)
remainder = sum(values) { |value, index| (index + 1) * value.to_i } % 11
values += "-#{remainder == 10 ? 'X' : remainder}"
end
private def self.generate_base13_isbn
values = Faker.regexify(/\d{12}/)
remainder = sum(values) { |value, index| index.even? ? value.to_i : value.to_i * 3 } % 10
values += "-#{(10 - remainder) % 10}"
end
private def self.sum(values)
values.split(//).each_with_index.reduce(0) do |sum, (value, index)|
sum + yield(value, index)
end
end
end
end

View File

@ -1,20 +1,59 @@
module Faker module Faker
class Commerce class Commerce < Base
def self.color def self.color
Faker.fetch(Data["color"]["name"]) Faker.fetch(Data["color"]["name"])
end end
def self.department uniquify_builder(color)
Faker.fetch(Data["commerce"]["department"])
def self.department(max = 3, fixed_amount = false)
num = max if fixed_amount
num ||= 1 + Faker.rng.rand(max)
categories = categories(num)
if num > 1
merge_categories(categories)
else
categories[0]
end
end end
uniquify_builder(department, max = 3, fixed_amount = false)
def self.material
product_name = Data["commerce"]["product_name"].as Hash
Faker.fetch(product_name["material"])
end
uniquify_builder(material)
def self.product_name def self.product_name
product_name = Data["commerce"]["product_name"] as Hash product_name = Data["commerce"]["product_name"].as Hash
Faker.fetch(product_name["adjective"]) + " " + Faker.fetch(product_name["material"]) + " " + Faker.fetch(product_name["product"]) Faker.fetch(product_name["adjective"]) + " " + Faker.fetch(product_name["material"]) + " " + Faker.fetch(product_name["product"])
end end
def self.price uniquify_builder(product_name)
(rand(100) + rand).round(2)
def self.price(range = 0.0..100.0)
(Faker.rng.rand(range) * 100).floor/100.0
end
uniquify_builder(price, range = 0.0..100.0)
private def self.categories(num)
categories = [] of String
while categories.size < num
category = Faker.fetch(Data["commerce"]["department"])
categories << category unless categories.includes?(category)
end
categories
end
private def self.merge_categories(categories)
separator = " & "
comma_separated = categories[0...-1].join(", ")
[comma_separated, categories[-1]].join(separator)
end end
end end
end end

View File

@ -1,26 +1,36 @@
module Faker module Faker
class Company class Company < Base
def self.name def self.name
Faker.fetch(Data["company"]["name"]) Faker.fetch(Data["company"]["name"])
end end
uniquify_builder(name)
def self.suffix def self.suffix
Faker.fetch(Data["company"]["suffix"]) Faker.fetch(Data["company"]["suffix"])
end end
uniquify_builder(suffix)
def self.catch_phrase def self.catch_phrase
data = Data["company"]["buzzwords"] as Array(Array(String)) data = Data["company"]["buzzwords"].as Array(Array(String))
Faker.fetch(data.flatten) Faker.fetch(data.flatten)
end end
uniquify_builder(catch_phrase)
def self.bs def self.bs
data = Data["company"]["bs"] as Array(Array(String)) data = Data["company"]["bs"].as Array(Array(String))
Faker.fetch(data.flatten) Faker.fetch(data.flatten)
end end
uniquify_builder(bs)
def self.logo def self.logo
rand_num = Random.rand(13) + 1 rand_num = Faker.rng.rand(13) + 1
"https://pigment.github.io/fake-logos/logos/medium/color/#{rand_num}.png" "https://pigment.github.io/fake-logos/logos/medium/color/#{rand_num}.png"
end end
uniquify_builder(logo)
end end
end end

74
src/faker/date.cr Normal file
View File

@ -0,0 +1,74 @@
module Faker
class Date < Base
def self.between(from : Time | String, to : Time | String) : Time
from = parse_date(from)
to = parse_date(to)
Time.unix(Faker.rand_in_range(from.to_unix, to.to_unix)).at_beginning_of_day
end
def self.between_except(from : Time | String, to : Time | String, excepted : Time | String)
raise ArgumentError.new("From date, to date and excepted date must not be the same") if from == to && to == excepted
excepted = parse_date(excepted)
loop do
date = between(from: from, to: to)
return date if date != excepted
end
end
def self.birthday(min_age : Int32 = 18, max_age : Int32 = 65) : Time
today = Time.utc
from = birthday_date(today, max_age)
to = birthday_date(today, min_age)
between(from, to)
end
def self.forward(days : Int32 = 365) : Time
from = Time.utc + 1.day
to = Time.utc + days.days
between(from: from, to: to)
end
def self.backward(days : Int32 = 365) : Time
from = Time.utc - days.days
to = Time.utc - 1.day
between(from: from, to: to)
end
def self.in_date_period(month : Int32? = nil, year : Int32 = Time.utc.year) : Time
from = Time.utc(year, month || 1, 1)
to_month = month || 12
end_day = Time.utc(year, to_month, 1).at_end_of_month.day
to = Time.utc(year, to_month, end_day)
between(from: from, to: to)
end
private def self.parse_date(date : String) : Time
Time.parse(date, "%Y-%m-%d", Time::Location::UTC)
end
private def self.parse_date(date : Time) : Time
date
end
private def self.birthday_date(date : Time, age : Int32) : Time
year = date.year - age
day =
if date.day == 29 && date.month == 2 && Time.leap_year?(year)
28
else
date.day
end
Time.utc(year, date.month, day)
end
end
end

View File

@ -1,8 +1,8 @@
module Faker module Faker
class Finance class Finance < Base
CREDIT_CARD_TYPES = (Data["credit_card"] as Hash).keys CREDIT_CARD_TYPES = (Data["credit_card"].as(Hash)).keys
def self.credit_card(types = [] of Array(String) : Array) def self.credit_card(types : Array = [] of Array(String))
types = CREDIT_CARD_TYPES if types.empty? types = CREDIT_CARD_TYPES if types.empty?
type = types.sample type = types.sample
@ -21,5 +21,6 @@ module Faker
template = template.gsub "L", luhn_digit.to_s template = template.gsub "L", luhn_digit.to_s
template template
end end
# TODO: uniquify_builder(credit_card, types : Array = [] of Array(String))
end end
end end

29
src/faker/hacker.cr Normal file
View File

@ -0,0 +1,29 @@
# Port of http://shinytoylabs.com/jargon/
module Faker
class Hacker < Base
def self.say_something_smart
phrases.sample(Faker.rng)
end
uniquify_builder(say_something_smart)
{% for data_type in %w(abbreviation adjective noun verb ingverb) %}
def self.{{data_type.id}}
Faker.fetch(Data["hacker"]["{{data_type.id}}"])
end
uniquify_builder({{data_type.id}})
{% end %}
def self.phrases
["If we #{verb} the #{noun}, we can get to the #{abbreviation} #{noun} through the #{adjective} #{abbreviation} #{noun}!",
"We need to #{verb} the #{adjective} #{abbreviation} #{noun}!",
"Try to #{verb} the #{abbreviation} #{noun}, maybe it will #{verb} the #{adjective} #{noun}!",
"You can't #{verb} the #{noun} without #{ingverb} the #{adjective} #{abbreviation} #{noun}!",
"Use the #{adjective} #{abbreviation} #{noun}, then you can #{verb} the #{adjective} #{noun}!",
"The #{abbreviation} #{noun} is down, #{verb} the #{adjective} #{noun} so we can #{verb} the #{abbreviation} #{noun}!",
"#{ingverb} the #{noun} won't do anything, we need to #{verb} the #{adjective} #{abbreviation} #{noun}!",
"I'll #{verb} the #{adjective} #{abbreviation} #{noun}, that should #{noun} the #{abbreviation} #{noun}!",
]
end
end
end

View File

@ -1,20 +1,26 @@
module Faker module Faker
class Internet class Internet < Base
def self.email(name = nil) def self.email(name = nil)
[user_name(name), domain_name].join("@") [user_name(name), domain_name].join("@")
end end
uniquify_builder(email, name = nil)
def self.free_email(name = nil) def self.free_email(name = nil)
[user_name(name), Faker.fetch(Data["internet"]["free_email"])].join("@") [user_name(name), Faker.fetch(Data["internet"]["free_email"])].join("@")
end end
uniquify_builder(free_email, name = nil)
def self.safe_email(name = nil) def self.safe_email(name = nil)
[user_name(name), "example." + %w(org com net).shuffle.first].join("@") [user_name(name), "example." + %w(org com net).shuffle(Faker.rng).first].join("@")
end end
uniquify_builder(safe_email, name = nil)
def self.user_name(specifier = nil, separators = %w(. _)) def self.user_name(specifier = nil, separators = %w(. _))
if specifier.is_a? String if specifier.is_a? String
return specifier.scan(/\w+/).map { |s| s[0] }.shuffle.join(separators.sample).downcase return specifier.scan(/\w+/).map { |s| s[0] }.shuffle(Faker.rng).join(separators.sample(Faker.rng)).downcase
elsif specifier.is_a? Int elsif specifier.is_a? Int
tries = 0 # Don't try forever in case we get something like 1_000_000. tries = 0 # Don't try forever in case we get something like 1_000_000.
result = "" result = ""
@ -40,65 +46,100 @@ module Faker
return result[0...specifier.max] return result[0...specifier.max]
end end
return name.scan(/\w+/).shuffle.map(&.[0]).join(separators.sample).downcase if name
[ [
->{ Name.first_name.gsub(/\W/, "").downcase }, ->{ Name.first_name.gsub(/\W/, "").downcase },
->{ ->{
[Name.first_name, Name.last_name].map { |n| [Name.first_name, Name.last_name].map { |n|
n.gsub(/\W/, "") n.gsub(/\W/, "")
}.join(separators.sample).downcase }.join(separators.sample(Faker.rng)).downcase
}, },
].sample.call ].sample(Faker.rng).call
end end
uniquify_builder(user_name, specifier = nil, separators = %w(. _))
def self.domain_name def self.domain_name
[domain_word, domain_suffix].join(".") [domain_word, domain_suffix].join(".")
end end
uniquify_builder(domain_name)
def self.domain_word def self.domain_word
Company.name.split(" ").first.gsub(/\W/, "").downcase Company.name.split(" ").first.gsub(/\W/, "").downcase
end end
uniquify_builder(domain_word)
def self.domain_suffix def self.domain_suffix
Faker.fetch(Data["internet"]["domain_suffix"]) Faker.fetch(Data["internet"]["domain_suffix"])
end end
uniquify_builder(domain_suffix)
def self.ip_v4_address def self.ip_v4_address
[ [
(2..254).to_a.sample, (2..254).to_a.sample(Faker.rng),
(2..254).to_a.sample, (2..254).to_a.sample(Faker.rng),
(2..254).to_a.sample, (2..254).to_a.sample(Faker.rng),
(2..254).to_a.sample, (2..254).to_a.sample(Faker.rng),
].join('.') ].join('.')
end end
uniquify_builder(ip_v4_address)
def self.ip_v6_address def self.ip_v6_address
ip_v6_space = (0..65535).to_a ip_v6_space = (0..65535).to_a
container = (1..8).map { |_| ip_v6_space.sample } container = (1..8).map { |_| ip_v6_space.sample(Faker.rng) }
container.map { |n| n.to_s(16) }.join(':') container.map { |n| n.to_s(16) }.join(':')
end end
uniquify_builder(ip_v6_address)
def self.mac_address(prefix = "") def self.mac_address(prefix = "")
prefix_digits = prefix.split(":").map { |d| d.to_i?(16) ? d.to_i?(16) : 0 } prefix_digits = prefix.split(":").map { |d| d.to_i?(16) ? d.to_i?(16) : 0 }
address_digits = (1..(6 - prefix_digits.size)).map { rand(256) } address_digits = (1..(6 - prefix_digits.size)).map { Faker.rng.rand(256) }
(prefix_digits + address_digits).map { |d| "%02x" % d }.join(":") (prefix_digits + address_digits).map { |d| "%02x" % d }.join(":")
end end
uniquify_builder(mac_address, prefix = "")
def self.url(host = domain_name, path = "/#{user_name}") def self.url(host = domain_name, path = "/#{user_name}")
"http://#{host}#{path}" "http://#{host}#{path}"
end end
uniquify_builder(url, host = domain_name, path = "/#{user_name}")
def self.slug(words = nil, glue = nil) def self.slug(words = nil, glue = nil)
glue ||= %w(- _ .).sample glue ||= %w(- _ .).sample(Faker.rng)
(words || Lorem.words(2).join(' ')).gsub(' ', glue).downcase (words || Lorem.words(2).join(' ')).gsub(' ', glue).downcase
end end
def self.password(min_length = 0) uniquify_builder(slug, words = nil, glue = nil)
temp = Lorem.words.join
while temp.size < min_length def self.password(min_length = 8, max_length = 16, mix_case = true, special_chars = false)
temp += Lorem.word temp = Lorem.characters(min_length)
diff_length = max_length - min_length
if diff_length > 0
diff_rand = Faker.rng.rand(diff_length + 1)
temp += Lorem.characters(diff_rand)
end end
temp = temp[0..min_length] if min_length > 0
if mix_case
temp = temp.gsub(/.{1,2}/) { |s| s.capitalize }
end
if special_chars
chars = %w(! @ # $ % ^ & *)
number_of_substitutions = Faker.rng.rand(min_length - 1) + 1 # substitute at least one character
number_of_substitutions.times do |i|
temp = temp.sub({temp[i] => chars[Faker.rng.rand(chars.size)]})
end
end
return temp return temp
end end
uniquify_builder(password, min_length = 8, max_length = 16, mix_case = true, special_chars = false)
end end
end end

View File

@ -1,31 +1,41 @@
module Faker module Faker
# Based on Perl"s Text::Lorem # Based on Perl"s Text::Lorem
class Lorem class Lorem < Base
def self.character def self.character
characters(1) characters(1)
end end
uniquify_builder(character)
def self.characters(char_count = 255) def self.characters(char_count = 255)
chars = ("a".."z").to_a + (0..9).to_a chars = ("a".."z").to_a + (0..9).to_a
Array(String).new(char_count < 0 ? 0 : char_count, "").map { chars.sample }.join("") Array(String).new(char_count < 0 ? 0 : char_count, "").map { chars.sample(Faker.rng) }.join("")
end end
uniquify_builder(characters)
def self.word def self.word
words = Data["lorem"]["words"] as Array words = Data["lorem"]["words"].as Array
Faker.fetch(words) Faker.fetch(words)
end end
def self.words(num = 3, supplemental = false) uniquify_builder(word)
words = Data["lorem"]["words"] as Array(String)
words += (Data["lorem"]["supplemental"] as Array(String)) if supplemental
words.shuffle[0, num] def self.words(num = 3, supplemental = false)
words = Data["lorem"]["words"].as Array(String)
words += (Data["lorem"]["supplemental"].as Array(String)) if supplemental
words.shuffle(Faker.rng)[0, num]
end end
uniquify_builder(words)
def self.sentence(word_count = 4, supplemental = false, random_words_to_add = 6) def self.sentence(word_count = 4, supplemental = false, random_words_to_add = 6)
words(word_count + rand(random_words_to_add.to_i).to_i, supplemental).join(" ").capitalize + "." words(word_count + Faker.rng.rand(random_words_to_add.to_i).to_i, supplemental).join(" ").capitalize + "."
end end
uniquify_builder(sentence)
def self.sentences(sentence_count = 3, supplemental = false) def self.sentences(sentence_count = 3, supplemental = false)
([] of String).tap do |sentences| ([] of String).tap do |sentences|
1.upto(sentence_count) do 1.upto(sentence_count) do
@ -34,10 +44,14 @@ module Faker
end end
end end
uniquify_builder(sentences)
def self.paragraph(sentence_count = 3, supplemental = false, random_sentences_to_add = 3) def self.paragraph(sentence_count = 3, supplemental = false, random_sentences_to_add = 3)
sentences(sentence_count + rand(random_sentences_to_add.to_i).to_i, supplemental).join(" ") sentences(sentence_count + Faker.rng.rand(random_sentences_to_add.to_i).to_i, supplemental).join(" ")
end end
uniquify_builder(paragraph)
def self.paragraphs(paragraph_count = 3, supplemental = false) def self.paragraphs(paragraph_count = 3, supplemental = false)
([] of String).tap do |paragraphs| ([] of String).tap do |paragraphs|
1.upto(paragraph_count) do 1.upto(paragraph_count) do
@ -45,5 +59,7 @@ module Faker
end end
end end
end end
uniquify_builder(paragraphs)
end end
end end

View File

@ -1,14 +1,17 @@
module Faker module Faker
class Name class Name < Base
{% for data_type in %w(first_name last_name name prefix suffix) %} {% for data_type in %w(first_name last_name name prefix suffix) %}
def self.{{data_type.id}} def self.{{data_type.id}}
Faker.fetch(Data["name"]["{{data_type.id}}"]) Faker.fetch(Data["name"]["{{data_type.id}}"])
end end
uniquify_builder({{data_type.id}})
{% end %} {% end %}
def self.title def self.title
title = Data["name"]["title"] as Hash title = Data["name"]["title"].as Hash
Faker.fetch(title["descriptor"]) + " " + Faker.fetch(title["level"]) + " " + Faker.fetch(title["job"]) Faker.fetch(title["descriptor"]) + " " + Faker.fetch(title["level"]) + " " + Faker.fetch(title["job"])
end end
uniquify_builder(title)
end end
end end

View File

@ -1,17 +1,67 @@
module Faker module Faker
class Number class Number < Base
def self.number(digits) def self.number(digits)
(1..digits).map { digit }.join "" (1..digits).map { digit }.join ""
end end
uniquify_builder(number, digits)
def self.digit def self.digit
rand(10).to_s Faker.rng.rand(10).to_s
end end
uniquify_builder(digit)
def self.decimal(l_digits, r_digits = 2) def self.decimal(l_digits, r_digits = 2)
l_d = number(l_digits) l_d = number(l_digits)
r_d = number(r_digits) r_d = number(r_digits)
"#{l_d}.#{r_d}" "#{l_d}.#{r_d}"
end end
uniquify_builder(decimal, l_digits, r_digits = 2)
def self.between(from = 1.00, to = 5000.00)
Faker.rand_in_range(from, to)
end
uniquify_builder(between)
def self.positive(from = 1.00, to = 5000.00)
random_number = between(from, to)
greater_than_zero(random_number)
end
uniquify_builder(positive)
def self.negative(from = -5000.00, to = -1.00)
random_number = between(from, to)
less_than_zero(random_number)
end
uniquify_builder(negative)
def self.hexadecimal(digits)
hex = ""
digits.times { hex += Faker.rng.rand(15).to_s(16) }
hex
end
uniquify_builder(hexadecimal)
private def self.greater_than_zero(number)
if number > 0
number
else
number * -1
end
end
private def self.less_than_zero(number)
if number < 0
number
else
number * -1
end
end
end end
end end

View File

@ -1,7 +1,9 @@
module Faker module Faker
class PhoneNumber class PhoneNumber < Base
def self.phone_number def self.phone_number
Faker.numerify(Faker.fetch(Data["phone_number"]["formats"])) Faker.numerify(Faker.fetch(Data["phone_number"]["formats"]))
end end
uniquify_builder(phone_number)
end end
end end

View File

@ -1,15 +1,21 @@
module Faker module Faker
class Team class Team < Base
def self.name def self.name
Faker.fetch(Data["team"]["name"]) Faker.fetch(Data["team"]["name"])
end end
uniquify_builder(name)
def self.creature def self.creature
Faker.fetch(Data["team"]["creature"]) Faker.fetch(Data["team"]["creature"])
end end
uniquify_builder(creature)
def self.state def self.state
Faker.fetch(Data["address"]["state"]) Faker.fetch(Data["address"]["state"])
end end
uniquify_builder(state)
end end
end end

View File

@ -1,3 +1,3 @@
module Faker module Faker
VERSION = "0.1.0" VERSION = "0.8.0"
end end