From 448cc4f365bf90e984ca5c340b4d7b978054f308 Mon Sep 17 00:00:00 2001 From: Stephen Date: Mon, 14 May 2018 23:06:18 -0700 Subject: [PATCH] Rubocop + fixes (#924) * Rubocop + fixes still has some errors * Readd travis script --- .rubocop.yml | 20 +++ Gemfile | 9 +- Gemfile.lock | 18 ++- Rakefile | 7 +- faker.gemspec | 25 ++-- lib/extensions/array.rb | 20 +-- lib/extensions/symbol.rb | 1 - lib/faker.rb | 61 ++++---- lib/faker/address.rb | 45 ++++-- lib/faker/app.rb | 4 +- lib/faker/avatar.rb | 4 +- lib/faker/bank.rb | 8 +- lib/faker/beer.rb | 2 +- lib/faker/bitcoin.rb | 9 +- lib/faker/breaking_bad.rb | 3 - lib/faker/business.rb | 3 +- lib/faker/chuck_norris.rb | 5 +- lib/faker/code.rb | 36 ++--- lib/faker/color.rb | 4 +- lib/faker/commerce.rb | 7 +- lib/faker/company.rb | 47 +++--- lib/faker/currency.rb | 1 - lib/faker/date.rb | 2 +- lib/faker/demographic.rb | 4 +- lib/faker/dr_who.rb | 11 +- lib/faker/dumb_and_dumber.rb | 2 +- lib/faker/dune.rb | 8 +- lib/faker/file.rb | 7 +- lib/faker/fillmurray.rb | 7 +- lib/faker/finance.rb | 7 +- lib/faker/food.rb | 2 +- lib/faker/hacker.rb | 20 ++- lib/faker/hipster.rb | 8 +- lib/faker/id_number.rb | 15 +- lib/faker/internet.rb | 108 ++++++------- lib/faker/job.rb | 9 +- lib/faker/lebowski.rb | 4 +- lib/faker/lorem.rb | 4 +- lib/faker/lorem_pixel.rb | 20 ++- lib/faker/lovecraft.rb | 9 +- lib/faker/markdown.rb | 6 +- lib/faker/measurement.rb | 40 +++-- lib/faker/michael_scott.rb | 2 +- lib/faker/music.rb | 2 +- lib/faker/name.rb | 5 +- lib/faker/number.rb | 24 +-- lib/faker/omniauth.rb | 166 ++++++++++---------- lib/faker/phone_number.rb | 26 ++-- lib/faker/placeholdit.rb | 4 +- lib/faker/rick_and_morty.rb | 2 +- lib/faker/science.rb | 2 - lib/faker/seinfeld.rb | 2 +- lib/faker/shakespeare.rb | 3 - lib/faker/simpsons.rb | 11 +- lib/faker/slack_emoji.rb | 2 - lib/faker/star_trek.rb | 4 +- lib/faker/star_wars.rb | 9 +- lib/faker/string.rb | 17 ++- lib/faker/stripe.rb | 13 +- lib/faker/team.rb | 1 - lib/faker/time.rb | 20 +-- lib/faker/twin_peaks.rb | 4 +- lib/faker/types.rb | 50 +++---- lib/faker/university.rb | 6 +- lib/faker/vehicle.rb | 19 ++- lib/faker/verb.rb | 2 +- lib/faker/version.rb | 2 +- lib/helpers/char.rb | 40 ++--- lib/helpers/unique_generator.rb | 6 + script/destroy | 2 +- script/generate | 2 +- script/txt2html | 33 ++-- tasks/test.rake | 6 +- tasks/website.rake | 8 +- test/test_array_sample_method_compat.rb | 17 +-- test/test_avatar.rb | 12 +- test/test_ca_cat_locale.rb | 4 +- test/test_country_code.rb | 1 - test/test_de_at_locale.rb | 2 - test/test_de_locale.rb | 6 +- test/test_determinism.rb | 31 ++-- test/test_en_au_locale.rb | 2 +- test/test_en_au_ocker_locale.rb | 2 +- test/test_en_ca_locale.rb | 1 - test/test_en_gb_locale.rb | 12 +- test/test_en_ind_locale.rb | 1 - test/test_en_locale.rb | 12 +- test/test_en_nz_locale.rb | 4 +- test/test_en_ug_locale.rb | 7 +- test/test_en_us_locale.rb | 6 +- test/test_es_locale.rb | 5 +- test/test_es_mx_locale.rb | 1 - test/test_fa_locale.rb | 1 - test/test_faker.rb | 6 +- test/test_faker_address.rb | 3 +- test/test_faker_ancient.rb | 1 - test/test_faker_app.rb | 21 ++- test/test_faker_aqua_teen_hunger_force.rb | 20 ++- test/test_faker_bank.rb | 7 +- test/test_faker_beer.rb | 4 +- test/test_faker_birthday_in_leap_year.rb | 6 +- test/test_faker_bitcoin.rb | 2 - test/test_faker_book.rb | 1 - test/test_faker_breaking_bad.rb | 1 - test/test_faker_business.rb | 2 - test/test_faker_cat.rb | 1 - test/test_faker_chuck_norris.rb | 1 - test/test_faker_city.rb | 29 ++-- test/test_faker_coffee.rb | 5 +- test/test_faker_color.rb | 2 +- test/test_faker_commerce.rb | 13 +- test/test_faker_company.rb | 17 +-- test/test_faker_date.rb | 22 +-- test/test_faker_demographic.rb | 2 +- test/test_faker_dessert.rb | 1 - test/test_faker_dr_who.rb | 12 +- test/test_faker_dumb_and_dumber.rb | 1 - test/test_faker_dune.rb | 9 +- test/test_faker_educator.rb | 2 - test/test_faker_elder_scrolls.rb | 1 - test/test_faker_family_guy.rb | 30 ++-- test/test_faker_file.rb | 6 +- test/test_faker_fillmurray.rb | 5 +- test/test_faker_food.rb | 6 +- test/test_faker_funny_name.rb | 1 - test/test_faker_hacker_talk.rb | 7 +- test/test_faker_hipster.rb | 17 +-- test/test_faker_internet.rb | 85 ++++++----- test/test_faker_job.rb | 1 - test/test_faker_kpop.rb | 1 - test/test_faker_lebowski.rb | 7 +- test/test_faker_lorem.rb | 25 ++-- test/test_faker_lovecraft.rb | 15 +- test/test_faker_markdown.rb | 23 ++- test/test_faker_measurement.rb | 6 +- test/test_faker_michael_scott.rb | 3 +- test/test_faker_movie.rb | 19 ++- test/test_faker_music.rb | 4 +- test/test_faker_name.rb | 3 +- test/test_faker_nation.rb | 6 +- test/test_faker_number.rb | 20 +-- test/test_faker_omniauth.rb | 175 +++++++++++----------- test/test_faker_one_piece.rb | 49 +++--- test/test_faker_pokemon.rb | 2 - test/test_faker_programming_language.rb | 28 ++-- test/test_faker_rock_band.rb | 3 +- test/test_faker_science.rb | 1 - test/test_faker_seinfeld.rb | 1 - test/test_faker_shakespeare.rb | 1 - test/test_faker_simpsons.rb | 9 +- test/test_faker_slack_emoji.rb | 5 +- test/test_faker_star_wars.rb | 6 +- test/test_faker_street.rb | 29 ++-- test/test_faker_string.rb | 11 +- test/test_faker_stripe.rb | 8 +- test/test_faker_superhero.rb | 1 - test/test_faker_team.rb | 2 - test/test_faker_time.rb | 34 ++--- test/test_faker_twin_peaks.rb | 2 +- test/test_faker_types.rb | 27 ++-- test/test_faker_umphreys_mcgee.rb | 1 - test/test_faker_unique_generator.rb | 1 - test/test_faker_university.rb | 3 - test/test_faker_vehicle.rb | 23 ++- test/test_faker_venture_bros.rb | 1 - test/test_faker_verb.rb | 1 - test/test_faker_witcher.rb | 7 +- test/test_faker_zip_code.rb | 22 +-- test/test_flexible.rb | 19 ++- test/test_fr_locale.rb | 4 +- test/test_helper.rb | 6 +- test/test_ko_locale.rb | 1 - test/test_locale.rb | 5 +- test/test_lorem_pixel.rb | 17 +-- test/test_pl_locale.rb | 10 +- test/test_placeholdit.rb | 19 ++- test/test_pt_locale.rb | 2 +- test/test_seeding.rb | 12 +- test/test_sv_locale.rb | 2 +- test/test_uk_locale.rb | 8 +- test/test_zh_cn_locale.rb | 1 - test/test_zh_locale.rb | 2 +- 182 files changed, 1117 insertions(+), 1180 deletions(-) create mode 100644 .rubocop.yml diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000000..2f7a23b713 --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,20 @@ +Metrics/LineLength: + Enabled: false +Metrics/MethodLength: + Enabled: false +Metrics/ClassLength: + Enabled: false +Metrics/BlockLength: + Enabled: false +Metrics/AbcSize: + Enabled: false +Metrics/PerceivedComplexity: + Enabled: false +Metrics/CyclomaticComplexity: + Enabled: false +Style/Documentation: + Enabled: false +Style/DateTime: + Enabled: false +Lint/UnifiedInteger: + Enabled: false diff --git a/Gemfile b/Gemfile index 2133c99bea..d85a14c69c 100644 --- a/Gemfile +++ b/Gemfile @@ -1,11 +1,4 @@ -source "https://rubygems.org" +source 'https://rubygems.org' # Specify your gem's dependencies in faker.gemspec gemspec - -group :development, :test do - gem "test-unit" - gem "rake" - gem "minitest" - gem "timecop" -end diff --git a/Gemfile.lock b/Gemfile.lock index e300ecf23b..9f57a1abf4 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -7,15 +7,30 @@ PATH GEM remote: https://rubygems.org/ specs: + ast (2.4.0) concurrent-ruby (1.0.5) i18n (0.9.1) concurrent-ruby (~> 1.0) minitest (5.10.3) + parallel (1.12.1) + parser (2.5.1.0) + ast (~> 2.4.0) power_assert (1.1.1) + powerpack (0.1.1) + rainbow (3.0.0) rake (12.3.0) + rubocop (0.55.0) + parallel (~> 1.10) + parser (>= 2.5) + powerpack (~> 0.1) + rainbow (>= 2.2.2, < 4.0) + ruby-progressbar (~> 1.7) + unicode-display_width (~> 1.0, >= 1.0.1) + ruby-progressbar (1.9.0) test-unit (3.2.6) power_assert timecop (0.9.1) + unicode-display_width (1.3.2) PLATFORMS ruby @@ -24,8 +39,9 @@ DEPENDENCIES faker! minitest rake + rubocop test-unit timecop BUNDLED WITH - 1.16.0 + 1.16.1.pre1 diff --git a/Rakefile b/Rakefile index a296670b72..7a5ce39912 100644 --- a/Rakefile +++ b/Rakefile @@ -1,4 +1,4 @@ -$:.unshift File.dirname(__FILE__) +$LOAD_PATH.unshift File.dirname(__FILE__) Dir['tasks/**/*.rake'].each { |rake| load rake } @@ -13,4 +13,7 @@ task :console do IRB.start end -task default: %w[test] +require 'rubocop/rake_task' +RuboCop::RakeTask.new + +task default: %w[test rubocop] diff --git a/faker.gemspec b/faker.gemspec index 1211bc9863..0ae1b657c8 100644 --- a/faker.gemspec +++ b/faker.gemspec @@ -1,20 +1,25 @@ -$:.push File.expand_path("../lib", __FILE__) -require "faker/version" +$LOAD_PATH.push File.expand_path('lib', __dir__) +require 'faker/version' Gem::Specification.new do |s| - s.name = "faker" + s.name = 'faker' s.version = Faker::VERSION s.platform = Gem::Platform::RUBY - s.authors = ["Benjamin Curtis"] - s.email = ["benjamin.curtis@gmail.com"] - s.homepage = "https://github.com/stympy/faker" - s.summary = %q{Easily generate fake data} - s.description = %q{Faker, a port of Data::Faker from Perl, is used to easily generate fake data: names, addresses, phone numbers, etc.} + s.authors = ['Benjamin Curtis'] + s.email = ['benjamin.curtis@gmail.com'] + s.homepage = 'https://github.com/stympy/faker' + s.summary = 'Easily generate fake data' + s.description = 'Faker, a port of Data::Faker from Perl, is used to easily generate fake data: names, addresses, phone numbers, etc.' s.license = 'MIT' s.add_runtime_dependency('i18n', '>= 0.7') + s.add_development_dependency('minitest') + s.add_development_dependency('rake') + s.add_development_dependency('rubocop') + s.add_development_dependency('test-unit') + s.add_development_dependency('timecop') s.required_ruby_version = '>= 2.1' - s.files = Dir['lib/**/*'] + %w(History.md License.txt CHANGELOG.md README.md) - s.require_paths = ["lib"] + s.files = Dir['lib/**/*'] + %w[History.md License.txt CHANGELOG.md README.md] + s.require_paths = ['lib'] end diff --git a/lib/extensions/array.rb b/lib/extensions/array.rb index c8cf8a8a33..7024d26e08 100644 --- a/lib/extensions/array.rb +++ b/lib/extensions/array.rb @@ -1,21 +1,21 @@ class Array - unless self.method_defined? :sample - def sample(n = nil) - #based on code from https://github.com/marcandre/backports - size = self.length - return self[Kernel.rand(size)] if n.nil? + unless method_defined? :sample + def sample(arr = nil) + # based on code from https://github.com/marcandre/backports + size = length + return self[Kernel.rand(size)] if arr.nil? - n = n.to_int - raise ArgumentError, "negative array size" if n < 0 + arr = arr.to_int + raise ArgumentError, 'negative array size' if arr < 0 - n = size if n > size + arr = size if arr > size result = Array.new(self) - n.times do |i| + arr.times do |i| r = i + Kernel.rand(size - i) result[i], result[r] = result[r], result[i] end - result[n..size] = [] + result[arr..size] = [] result end end diff --git a/lib/extensions/symbol.rb b/lib/extensions/symbol.rb index 90fa0d68d8..d302ee63ab 100644 --- a/lib/extensions/symbol.rb +++ b/lib/extensions/symbol.rb @@ -6,4 +6,3 @@ def downcase end end end - diff --git a/lib/faker.rb b/lib/faker.rb index f6d8645c9b..d311b458af 100644 --- a/lib/faker.rb +++ b/lib/faker.rb @@ -1,9 +1,7 @@ -# -*- coding: utf-8 -*- -mydir = File.expand_path(File.dirname(__FILE__)) +mydir = __dir__ begin require 'psych' -rescue LoadError end require 'i18n' @@ -15,7 +13,6 @@ I18n.load_path += Dir[File.join(mydir, 'locales', '**/*.yml')] I18n.reload! if I18n.backend.initialized? - module Faker class Config @locale = nil @@ -45,9 +42,9 @@ class Base Letters = ULetters + Array('a'..'z') class << self - ## make sure numerify results doesn’t start with a zero + ## make sure numerify results do not start with a zero def numerify(number_string) - number_string.sub(/#/) { (rand(9)+1).to_s }.gsub(/#/) { rand(10).to_s } + number_string.sub(/#/) { rand(1..9).to_s }.gsub(/#/) { rand(10).to_s } end def letterify(letter_string) @@ -77,26 +74,26 @@ def bothify(string) # # "U3V 3TP" # - def regexify(re) - re = re.source if re.respond_to?(:source) # Handle either a Regexp or a String that looks like a Regexp - re. - gsub(/^\/?\^?/, '').gsub(/\$?\/?$/, ''). # Ditch the anchors - gsub(/\{(\d+)\}/, '{\1,\1}').gsub(/\?/, '{0,1}'). # All {2} become {2,2} and ? become {0,1} - gsub(/(\[[^\]]+\])\{(\d+),(\d+)\}/) {|match| $1 * sample(Array(Range.new($2.to_i, $3.to_i))) }. # [12]{1,2} becomes [12] or [12][12] - gsub(/(\([^\)]+\))\{(\d+),(\d+)\}/) {|match| $1 * sample(Array(Range.new($2.to_i, $3.to_i))) }. # (12|34){1,2} becomes (12|34) or (12|34)(12|34) - gsub(/(\\?.)\{(\d+),(\d+)\}/) {|match| $1 * sample(Array(Range.new($2.to_i, $3.to_i))) }. # A{1,2} becomes A or AA or \d{3} becomes \d\d\d - gsub(/\((.*?)\)/) {|match| sample(match.gsub(/[\(\)]/, '').split('|')) }. # (this|that) becomes 'this' or 'that' - gsub(/\[([^\]]+)\]/) {|match| match.gsub(/(\w\-\w)/) {|range| sample(Array(Range.new(*range.split('-')))) } }. # All A-Z inside of [] become C (or X, or whatever) - gsub(/\[([^\]]+)\]/) {|match| sample($1.split('')) }. # All [ABC] become B (or A or C) - gsub('\d') {|match| sample(Numbers) }. - gsub('\w') {|match| sample(Letters) } + def regexify(reg) + reg = reg.source if reg.respond_to?(:source) # Handle either a Regexp or a String that looks like a Regexp + reg + .gsub(%r{^\/?\^?}, '').gsub(%r{\$?\/?$}, '') # Ditch the anchors + .gsub(/\{(\d+)\}/, '{\1,\1}').gsub(/\?/, '{0,1}') # All {2} become {2,2} and ? become {0,1} + .gsub(/(\[[^\]]+\])\{(\d+),(\d+)\}/) { |_match| Regexp.last_match(1) * sample(Array(Range.new(Regexp.last_match(2).to_i, Regexp.last_match(3).to_i))) } # [12]{1,2} becomes [12] or [12][12] + .gsub(/(\([^\)]+\))\{(\d+),(\d+)\}/) { |_match| Regexp.last_match(1) * sample(Array(Range.new(Regexp.last_match(2).to_i, Regexp.last_match(3).to_i))) } # (12|34){1,2} becomes (12|34) or (12|34)(12|34) + .gsub(/(\\?.)\{(\d+),(\d+)\}/) { |_match| Regexp.last_match(1) * sample(Array(Range.new(Regexp.last_match(2).to_i, Regexp.last_match(3).to_i))) } # A{1,2} becomes A or AA or \d{3} becomes \d\d\d + .gsub(/\((.*?)\)/) { |match| sample(match.gsub(/[\(\)]/, '').split('|')) } # (this|that) becomes 'this' or 'that' + .gsub(/\[([^\]]+)\]/) { |match| match.gsub(/(\w\-\w)/) { |range| sample(Array(Range.new(*range.split('-')))) } } # All A-Z inside of [] become C (or X, or whatever) + .gsub(/\[([^\]]+)\]/) { |_match| sample(Regexp.last_match(1).split('')) } # All [ABC] become B (or A or C) + .gsub('\d') { |_match| sample(Numbers) } + .gsub('\w') { |_match| sample(Letters) } end # Helper for the common approach of grabbing a translation # with an array of values and selecting one of them. def fetch(key) fetched = sample(translate("faker.#{key}")) - if fetched && fetched.match(/^\//) && fetched.match(/\/$/) # A regex + if fetched && fetched.match(%r{^\/}) && fetched.match(%r{\/$}) # A regex regexify(fetched) else fetched @@ -108,7 +105,7 @@ def fetch(key) def fetch_all(key) fetched = translate("faker.#{key}") fetched = fetched.last if fetched.size <= 1 - if !fetched.respond_to?(:sample) && fetched.match(/^\//) && fetched.match(/\/$/) # A regex + if !fetched.respond_to?(:sample) && fetched.match(%r{^\/}) && fetched.match(%r{\/$}) # A regex regexify(fetched) else fetched @@ -120,7 +117,7 @@ def fetch_all(key) # formatted translation: e.g., "#{first_name} #{last_name}". def parse(key) fetched = fetch(key) - parts = fetched.scan(/(\(?)#\{([A-Za-z]+\.)?([^\}]+)\}([^#]+)?/).map {|prefix, kls, meth, etc| + parts = fetched.scan(/(\(?)#\{([A-Za-z]+\.)?([^\}]+)\}([^#]+)?/).map do |prefix, kls, meth, etc| # If the token had a class Prefix (e.g., Name.first_name) # grab the constant, otherwise use self cls = kls ? Faker.const_get(kls.chop) : self @@ -134,8 +131,8 @@ def parse(key) text += cls.respond_to?(meth) ? cls.send(meth) : fetch("#{(kls || self).to_s.split('::').last.downcase}.#{meth.downcase}") # And tack on spaces, commas, etc. left over in the string - text += etc.to_s - } + text + etc.to_s + end # If the fetched key couldn't be parsed, then fallback to numerify parts.any? ? parts.join : numerify(fetched) end @@ -146,7 +143,7 @@ def translate(*args) opts = args.last.is_a?(Hash) ? args.pop : {} opts[:locale] ||= Faker::Config.locale opts[:raise] = true - I18n.translate(*(args.push(opts))) + I18n.translate(*args.push(opts)) rescue I18n::MissingTranslationData opts = args.last.is_a?(Hash) ? args.pop : {} opts[:locale] = :en @@ -154,7 +151,7 @@ def translate(*args) # Super-simple fallback -- fallback to en if the # translation was missing. If the translation isn't # in en either, then it will raise again. - I18n.translate(*(args.push(opts))) + I18n.translate(*args.push(opts)) end # Executes block with given locale set. @@ -175,17 +172,21 @@ def flexible(key) # name: # girls_name: ["Alice", "Cheryl", "Tatiana"] # Then you can call Faker::Name.girls_name and it will act like #first_name - def method_missing(m, *args, &block) + def method_missing(mth, *args, &block) super unless @flexible_key # Use the alternate form of translate to get a nil rather than a "missing translation" string - if translation = translate(:faker)[@flexible_key][m] + if (translation = translate(:faker)[@flexible_key][mth]) sample(translation) else super end end + def respond_to_missing?(method_name, include_private = false) + super + end + # Generates a random value between the interval def rand_in_range(from, to) from, to = to, from if to < from @@ -193,7 +194,7 @@ def rand_in_range(from, to) end def unique(max_retries = 10_000) - @unique_generator ||= UniqueGenerator.new(self, max_retries) + @unique ||= UniqueGenerator.new(self, max_retries) end def sample(list) @@ -217,7 +218,7 @@ def rand(max = nil) end end -Dir.glob(File.join(File.dirname(__FILE__), 'faker','*.rb')).sort.each {|f| require f } +Dir.glob(File.join(File.dirname(__FILE__), 'faker', '*.rb')).sort.each { |f| require f } require 'extensions/array' require 'extensions/symbol' diff --git a/lib/faker/address.rb b/lib/faker/address.rb index f74f455db1..c7af355f58 100644 --- a/lib/faker/address.rb +++ b/lib/faker/address.rb @@ -28,7 +28,7 @@ def community end def zip_code(state_abbreviation = '') - return bothify(fetch('address.postcode')) if state_abbreviation === '' + return bothify(fetch('address.postcode')) if state_abbreviation.empty? # provide a zip code that is valid for the state provided # see http://www.fincen.gov/forms/files/us_state_territory_zip_codes.pdf @@ -39,17 +39,40 @@ def time_zone fetch('address.time_zone') end - alias_method :zip, :zip_code - alias_method :postcode, :zip_code + alias zip zip_code + alias postcode zip_code - def street_suffix; fetch('address.street_suffix'); end - def city_suffix; fetch('address.city_suffix'); end - def city_prefix; fetch('address.city_prefix'); end - def state_abbr; fetch('address.state_abbr'); end - def state; fetch('address.state'); end - def country; fetch('address.country'); end - def country_code; fetch('address.country_code'); end - def country_code_long; fetch('address.country_code_long'); end + def street_suffix + fetch('address.street_suffix') + end + + def city_suffix + fetch('address.city_suffix') + end + + def city_prefix + fetch('address.city_prefix') + end + + def state_abbr + fetch('address.state_abbr') + end + + def state + fetch('address.state') + end + + def country + fetch('address.country') + end + + def country_code + fetch('address.country_code') + end + + def country_code_long + fetch('address.country_code_long') + end def latitude ((rand * 180) - 90).to_s diff --git a/lib/faker/app.rb b/lib/faker/app.rb index 3be17c4393..b0d503d88f 100644 --- a/lib/faker/app.rb +++ b/lib/faker/app.rb @@ -1,7 +1,6 @@ module Faker class App < Base class << self - def name fetch('app.name') end @@ -15,9 +14,8 @@ def author end def semantic_version(major: 0..9, minor: 0..9, patch: 1..9) - [ major, minor, patch ].map {|chunk| sample(Array(chunk)) }.join('.') + [major, minor, patch].map { |chunk| sample(Array(chunk)) }.join('.') end - end end end diff --git a/lib/faker/avatar.rb b/lib/faker/avatar.rb index 614451d25c..cdf839be44 100644 --- a/lib/faker/avatar.rb +++ b/lib/faker/avatar.rb @@ -1,10 +1,10 @@ module Faker class Avatar < Base class << self - SUPPORTED_FORMATS = %w(png jpg bmp) + SUPPORTED_FORMATS = %w[png jpg bmp].freeze def image(slug = nil, size = '300x300', format = 'png', set = 'set1', bgset = nil) - raise ArgumentError, "Size should be specified in format 300x300" unless size.match(/^[0-9]+x[0-9]+$/) + raise ArgumentError, 'Size should be specified in format 300x300' unless size =~ /^[0-9]+x[0-9]+$/ raise ArgumentError, "Supported formats are #{SUPPORTED_FORMATS.join(', ')}" unless SUPPORTED_FORMATS.include?(format) slug ||= Faker::Lorem.words.join bgset_query = "&bgset=#{bgset}" if bgset diff --git a/lib/faker/bank.rb b/lib/faker/bank.rb index 658619e6e2..c8550d3a70 100644 --- a/lib/faker/bank.rb +++ b/lib/faker/bank.rb @@ -34,12 +34,12 @@ def iban(country_code = 'GB') # source: https://en.wikipedia.org/wiki/International_Bank_Account_Number#Validating_the_IBAN def iban_checksum(country_code, account) # Converts letters to numbers according the iban rules, A=10..Z=35 - account_to_number = "#{account}#{country_code}00".upcase.chars.map { |d| - d.match(/[A-Z]/) ? (d.ord - 55).to_s : d - }.join.to_i + account_to_number = "#{account}#{country_code}00".upcase.chars.map do |d| + d =~ /[A-Z]/ ? (d.ord - 55).to_s : d + end.join.to_i # This is answer to (iban_to_num + checksum) % 97 == 1 - checksum = ( 1 - account_to_number ) % 97 + checksum = (1 - account_to_number) % 97 # Use leftpad to make the size always to 2 checksum.to_s.rjust(2, '0') diff --git a/lib/faker/beer.rb b/lib/faker/beer.rb index d87f4bd35e..74280c8023 100644 --- a/lib/faker/beer.rb +++ b/lib/faker/beer.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + module Faker class Beer < Base flexible :beer diff --git a/lib/faker/bitcoin.rb b/lib/faker/bitcoin.rb index 0542d1dd5f..f084365eed 100644 --- a/lib/faker/bitcoin.rb +++ b/lib/faker/bitcoin.rb @@ -4,11 +4,10 @@ module Faker class Bitcoin < Base class << self - PROTOCOL_VERSIONS = { main: 0, testnet: 111 - } + }.freeze def address address_for(:main) @@ -25,16 +24,16 @@ def base58(str) base = alphabet.size lv = 0 - str.split('').reverse.each_with_index { |v,i| lv += v.unpack('C')[0] * 256**i } + str.split('').reverse.each_with_index { |v, i| lv += v.unpack('C')[0] * 256**i } ret = '' - while lv > 0 do + while lv > 0 lv, mod = lv.divmod(base) ret << alphabet[mod] end npad = str.match(/^#{0.chr}*/)[0].to_s.size - '1'*npad + ret.reverse + '1' * npad + ret.reverse end def address_for(network) diff --git a/lib/faker/breaking_bad.rb b/lib/faker/breaking_bad.rb index 9797200f94..628463e092 100644 --- a/lib/faker/breaking_bad.rb +++ b/lib/faker/breaking_bad.rb @@ -1,9 +1,7 @@ -# encoding: utf-8 # frozen_string_literal: true module Faker class BreakingBad < Base - def self.character fetch('breaking_bad.character') end @@ -11,6 +9,5 @@ def self.character def self.episode fetch('breaking_bad.episode') end - end end diff --git a/lib/faker/business.rb b/lib/faker/business.rb index 4b5385789f..a19843345f 100644 --- a/lib/faker/business.rb +++ b/lib/faker/business.rb @@ -10,13 +10,12 @@ def credit_card_number end def credit_card_expiry_date - ::Date.today + (365 * (rand(4) + 1)) + ::Date.today + (365 * rand(1..4)) end def credit_card_type fetch('business.credit_card_types') end end - end end diff --git a/lib/faker/chuck_norris.rb b/lib/faker/chuck_norris.rb index a52b917b24..07d4efefe6 100644 --- a/lib/faker/chuck_norris.rb +++ b/lib/faker/chuck_norris.rb @@ -4,8 +4,9 @@ class ChuckNorris < Base class << self # from: https://github.com/jenkinsci/chucknorris-plugin/blob/master/src/main/java/hudson/plugins/chucknorris/FactGenerator.java - def fact; fetch('chuck_norris.fact'); end - + def fact + fetch('chuck_norris.fact') + end end end end diff --git a/lib/faker/code.rb b/lib/faker/code.rb index 61fa92fd7a..b99c4de354 100644 --- a/lib/faker/code.rb +++ b/lib/faker/code.rb @@ -2,11 +2,10 @@ module Faker class Code < Base flexible :code class << self - # Generates a 10 digit NPI (National Provider Identifier # issued to health care providers in the United States) def npi - rand(10 ** 10).to_s.rjust(10, '0') + rand(10**10).to_s.rjust(10, '0') end # By default generates 10 sign isbn code in format 123456789-X @@ -49,20 +48,19 @@ def asin fetch('code.asin') end - private + private # Reporting body identifier - RBI = %w(01 10 30 33 35 44 45 49 50 51 52 53 54 86 91 98 99).freeze + RBI = %w[01 10 30 33 35 44 45 49 50 51 52 53 54 86 91 98 99].freeze def generate_imei - pos = 0 str = Array.new(15, 0) sum = 0 t = 0 len_offset = 0 len = 15 - # Fill in the first two values of the string based with the specified prefix. + # Fill in the first two values of the string based with the specified prefix. # Reporting Body Identifier list: http://en.wikipedia.org/wiki/Reporting_Body_Identifier arr = sample(RBI) str[0] = arr[0].to_i @@ -78,12 +76,10 @@ def generate_imei # Calculate the Luhn checksum of the values thus far len_offset = (len + 1) % 2 (0..(len - 1)).each do |position| - if (position + len_offset) % 2 != 0 + if (position + len_offset).odd? t = str[position] * 2 - if t > 9 - t -= 9 - end + t -= 9 if t > 9 sum += t else @@ -110,37 +106,37 @@ def generate_base13_isbn values << "-#{((10 - remainder) % 10)}" end - def sum(values, &block) + def sum(values) values.split(//).each_with_index.inject(0) do |sum, (value, index)| - sum + block.call(value, index) + sum + yield(value, index) end end def generate_base8_ean values = regexify(/\d{7}/) - check_digit = 10 - values.split(//).each_with_index.inject(0){ |s, (v, i)| s + v.to_i * EAN_CHECK_DIGIT8[i] } % 10 + check_digit = 10 - values.split(//).each_with_index.inject(0) { |s, (v, i)| s + v.to_i * EAN_CHECK_DIGIT8[i] } % 10 values << (check_digit == 10 ? 0 : check_digit).to_s end def generate_base13_ean values = regexify(/\d{12}/) - check_digit = 10 - values.split(//).each_with_index.inject(0){ |s, (v, i)| s + v.to_i * EAN_CHECK_DIGIT13[i] } % 10 + check_digit = 10 - values.split(//).each_with_index.inject(0) { |s, (v, i)| s + v.to_i * EAN_CHECK_DIGIT13[i] } % 10 values << (check_digit == 10 ? 0 : check_digit).to_s end - EAN_CHECK_DIGIT8 = [3, 1, 3, 1, 3, 1, 3] - EAN_CHECK_DIGIT13 = [1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3] + EAN_CHECK_DIGIT8 = [3, 1, 3, 1, 3, 1, 3].freeze + EAN_CHECK_DIGIT13 = [1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3].freeze def rut_verificator_digit(rut) - total = rut.to_s.rjust(8, '0').split(//).zip(%w(3 2 7 6 5 4 3 2)).collect{|a, b| a.to_i * b.to_i}.inject(:+) + total = rut.to_s.rjust(8, '0').split(//).zip(%w[3 2 7 6 5 4 3 2]).collect { |a, b| a.to_i * b.to_i }.inject(:+) (11 - total % 11).to_s.gsub(/10/, 'k').gsub(/11/, '0') end def generate_nric_check_alphabet(values, prefix) - weight = %w(2 7 6 5 4 3 2) + weight = %w[2 7 6 5 4 3 2] total = values.split(//).zip(weight).collect { |a, b| a.to_i * b.to_i }.inject(:+) - total = total + 4 if prefix == 'T' - %w(A B C D E F G H I Z J)[10 - total % 11] + total += 4 if prefix == 'T' + %w[A B C D E F G H I Z J][10 - total % 11] end end end diff --git a/lib/faker/color.rb b/lib/faker/color.rb index e9e48ef854..9bf18ca544 100644 --- a/lib/faker/color.rb +++ b/lib/faker/color.rb @@ -2,7 +2,7 @@ module Faker class Color < Base class << self def hex_color - '#%06x' % (rand * 0xffffff) + format('#%06x', (rand * 0xffffff)) end def color_name @@ -14,7 +14,7 @@ def single_rgb_color end def rgb_color - 3.times.collect { single_rgb_color } + Array.new(3) { single_rgb_color } end # returns [hue, saturation, lightness] diff --git a/lib/faker/commerce.rb b/lib/faker/commerce.rb index b6288d009d..40a3012c31 100644 --- a/lib/faker/commerce.rb +++ b/lib/faker/commerce.rb @@ -1,6 +1,5 @@ module Faker class Commerce < Base - class << self def color fetch('color.name') @@ -32,11 +31,11 @@ def material fetch('commerce.product_name.material') end - def price(range=0..100.0, as_string=false) - price = (rand(range) * 100).floor/100.0 + def price(range = 0..100.0, as_string = false) + price = (rand(range) * 100).floor / 100.0 if as_string price_parts = price.to_s.split('.') - price = price_parts[0] + '.' + price_parts[-1].ljust(2, "0") + price = price_parts[0] + '.' + price_parts[-1].ljust(2, '0') end price end diff --git a/lib/faker/company.rb b/lib/faker/company.rb index 1a849b15ed..d061a8b4bc 100644 --- a/lib/faker/company.rb +++ b/lib/faker/company.rb @@ -17,7 +17,7 @@ def industry # Generate a buzzword-laden catch phrase. def catch_phrase - translate('faker.company.buzzwords').collect {|list| sample(list) }.join(' ') + translate('faker.company.buzzwords').collect { |list| sample(list) }.join(' ') end def buzzword @@ -26,29 +26,31 @@ def buzzword # When a straight answer won't do, BS to the rescue! def bs - translate('faker.company.bs').collect {|list| sample(list) }.join(' ') + translate('faker.company.bs').collect { |list| sample(list) }.join(' ') end def ein - ('%09d' % rand(10 ** 9)).gsub(/(\d{2})(\d{7})/, '\\1-\\2') + format('%09d', rand(10**9)).gsub(/(\d{2})(\d{7})/, '\\1-\\2') end def duns_number - ('%09d' % rand(10 ** 9)).gsub(/(\d{2})(\d{3})(\d{4})/, '\\1-\\2-\\3') + format('%09d', rand(10**9)).gsub(/(\d{2})(\d{3})(\d{4})/, '\\1-\\2-\\3') end # Get a random company logo url in PNG format. def logo - rand_num = rand(13) + 1 + rand_num = rand(1..13) "https://pigment.github.io/fake-logos/logos/medium/color/#{rand_num}.png" end + # rubocop:disable Style/AsciiComments # Get a random Spanish organization number. See more here https://es.wikipedia.org/wiki/Número_de_identificación_fiscal + # rubocop:enable Style/AsciiComments def spanish_organisation_number # Valid leading character: A, B, C, D, E, F, G, H, J, N, P, Q, R, S, U, V, W # 7 digit numbers - letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'N', 'P', 'Q', 'R', 'S', 'U', 'V', 'W'] - base = [sample(letters), ('%07d' % rand(10 ** 7))].join + letters = %w[A B C D E F G H J N P Q R S U V W] + base = [sample(letters), format('%07d', rand(10**7))].join base end @@ -57,7 +59,7 @@ def swedish_organisation_number # Valid leading digit: 1, 2, 3, 5, 6, 7, 8, 9 # Valid third digit: >= 2 # Last digit is a control digit - base = [sample([1, 2, 3, 5, 6, 7, 8, 9]), sample((0..9).to_a), sample((2..9).to_a), ('%06d' % rand(10 ** 6))].join + base = [sample([1, 2, 3, 5, 6, 7, 8, 9]), sample((0..9).to_a), sample((2..9).to_a), format('%06d', rand(10**6))].join base + luhn_algorithm(base).to_s end @@ -78,14 +80,14 @@ def norwegian_organisation_number # Valid leading digit: 8, 9 mod11_check = nil while mod11_check.nil? - base = [sample([8, 9]), ('%07d' % rand(10 ** 7))].join + base = [sample([8, 9]), format('%07d', rand(10**7))].join mod11_check = mod11(base) end base + mod11_check.to_s end def australian_business_number - base = ('%09d' % rand(10 ** 9)) + base = format('%09d', rand(10**9)) abn = "00#{base}" (99 - (abn_checksum(abn) % 89)).to_s + base @@ -95,7 +97,7 @@ def profession fetch('company.profession') end - private + private # Mod11 functionality from https://github.com/badmanski/mod11/blob/master/lib/mod11.rb def mod11(number) @@ -122,11 +124,11 @@ def luhn_algorithm(number) multiplications = [] number.split(//).each_with_index do |digit, i| - if i.even? - multiplications << digit.to_i * 2 - else - multiplications << digit.to_i - end + multiplications << if i.even? + digit.to_i * 2 + else + digit.to_i + end end sum = 0 @@ -137,17 +139,17 @@ def luhn_algorithm(number) end end - if sum % 10 == 0 - control_digit = 0 - else - control_digit = (sum / 10 + 1) * 10 - sum - end + control_digit = if (sum % 10).zero? + 0 + else + (sum / 10 + 1) * 10 - sum + end control_digit end def abn_checksum(abn) - abn_weights = [10,1,3,5,7,9,11,13,15,17,19] + abn_weights = [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19] sum = 0 abn_weights.each_with_index do |weight, i| @@ -156,7 +158,6 @@ def abn_checksum(abn) sum end - end end end diff --git a/lib/faker/currency.rb b/lib/faker/currency.rb index f76e3f1450..9b2f5bf12d 100644 --- a/lib/faker/currency.rb +++ b/lib/faker/currency.rb @@ -1,7 +1,6 @@ module Faker class Currency < Base class << self - def name fetch('currency.name') end diff --git a/lib/faker/date.rb b/lib/faker/date.rb index c5601af209..7c8345c877 100644 --- a/lib/faker/date.rb +++ b/lib/faker/date.rb @@ -9,7 +9,7 @@ def between(from, to) end def between_except(from, to, excepted) - raise ArgumentError, "From date, to date and excepted date must not be the same" if from == to && to == excepted + raise ArgumentError, 'From date, to date and excepted date must not be the same' if from == to && to == excepted excepted = get_date_object(excepted) loop do diff --git a/lib/faker/demographic.rb b/lib/faker/demographic.rb index 666a940e01..cf3051d982 100644 --- a/lib/faker/demographic.rb +++ b/lib/faker/demographic.rb @@ -25,9 +25,9 @@ def height(unit = :metric) case unit when :imperial inches = rand_in_range(57, 86) - return "#{inches / 12} ft, #{inches % 12} in" + "#{inches / 12} ft, #{inches % 12} in" when :metric - return rand_in_range(1.45, 2.13).round(2).to_s + rand_in_range(1.45, 2.13).round(2).to_s end end end diff --git a/lib/faker/dr_who.rb b/lib/faker/dr_who.rb index 81fc96ad3b..05f6b69be7 100644 --- a/lib/faker/dr_who.rb +++ b/lib/faker/dr_who.rb @@ -1,10 +1,7 @@ -#encoding: utf-8 -#frozen_string_literal: true +# frozen_string_literal: true module Faker - class DrWho < Base - def self.character fetch('dr_who.character') end @@ -28,7 +25,5 @@ def self.villian def self.specie fetch('dr_who.species') end - - end #class DrWho - -end #module Faker + end +end diff --git a/lib/faker/dumb_and_dumber.rb b/lib/faker/dumb_and_dumber.rb index 5d49201c9b..cb92bd1ef6 100644 --- a/lib/faker/dumb_and_dumber.rb +++ b/lib/faker/dumb_and_dumber.rb @@ -4,7 +4,7 @@ class << self def actor fetch('dumb_and_dumber.actors') end - + def character fetch('dumb_and_dumber.characters') end diff --git a/lib/faker/dune.rb b/lib/faker/dune.rb index 5d8b5e2cac..4b5461f995 100644 --- a/lib/faker/dune.rb +++ b/lib/faker/dune.rb @@ -26,11 +26,11 @@ def quote(character = nil) unless quoted_characters.include?(character.to_sym) raise ArgumentError, - "Characters quoted can be left blank or #{quoted_characters.join(', ')}" + "Characters quoted can be left blank or #{quoted_characters.join(', ')}" end end - return fetch('dune.quotes.' + character) + fetch('dune.quotes.' + character) end def saying(source = nil) @@ -43,11 +43,11 @@ def saying(source = nil) unless sourced_sayings.include?(source.to_sym) raise ArgumentError, - "Sources quoted in sayings can be left blank or #{sourced_sayings.join(', ')}" + "Sources quoted in sayings can be left blank or #{sourced_sayings.join(', ')}" end end - return fetch('dune.sayings.' + source) + fetch('dune.sayings.' + source) end end end diff --git a/lib/faker/file.rb b/lib/faker/file.rb index aeb2bde832..1a7791bcce 100644 --- a/lib/faker/file.rb +++ b/lib/faker/file.rb @@ -1,7 +1,6 @@ module Faker class File < Base class << self - def extension fetch('file.extension') end @@ -11,14 +10,12 @@ def mime_type end def file_name(dir = nil, name = nil, ext = nil, directory_separator = '/') - - dir = Faker::Internet::slug unless dir - name = Faker::Lorem::word.downcase unless name + dir ||= Faker::Internet.slug + name ||= Faker::Lorem.word.downcase ext ||= extension [dir, name].join(directory_separator) + ".#{ext}" end - end end end diff --git a/lib/faker/fillmurray.rb b/lib/faker/fillmurray.rb index 9c26d510fe..3b8c3e8fd8 100644 --- a/lib/faker/fillmurray.rb +++ b/lib/faker/fillmurray.rb @@ -1,11 +1,10 @@ module Faker class Fillmurray < Base class << self - def image(grayscale = false, width = 200, height = 200) - raise ArgumentError, "Width should be a number" unless width.to_s.match(/^\d+$/) - raise ArgumentError, "Height should be a number" unless height.to_s.match(/^\d+$/) - raise ArgumentError, "Grayscale should be a boolean" unless [true, false].include?(grayscale) + raise ArgumentError, 'Width should be a number' unless width.to_s =~ /^\d+$/ + raise ArgumentError, 'Height should be a number' unless height.to_s =~ /^\d+$/ + raise ArgumentError, 'Grayscale should be a boolean' unless [true, false].include?(grayscale) grayscale == true ? "https://fillmurray.com/g/#{width}/#{height}" : "https://fillmurray.com/#{width}/#{height}" end diff --git a/lib/faker/finance.rb b/lib/faker/finance.rb index c2f32945f2..51b70db399 100644 --- a/lib/faker/finance.rb +++ b/lib/faker/finance.rb @@ -1,9 +1,8 @@ module Faker class Finance < Base - - CREDIT_CARD_TYPES = [:visa, :mastercard, :discover, :american_express, - :diners_club, :jcb, :switch, :solo, :dankort, - :maestro, :forbrugsforeningen, :laser].freeze + CREDIT_CARD_TYPES = %i[visa mastercard discover american_express + diners_club jcb switch solo dankort + maestro forbrugsforeningen laser].freeze class << self def credit_card(*types) diff --git a/lib/faker/food.rb b/lib/faker/food.rb index f44035f465..b3de3f54a6 100644 --- a/lib/faker/food.rb +++ b/lib/faker/food.rb @@ -20,7 +20,7 @@ def spice def measurement fetch('food.measurement_sizes') + ' ' + fetch('food.measurements') end - + def metric_measurement fetch('food.metric_measurements') end diff --git a/lib/faker/hacker.rb b/lib/faker/hacker.rb index eec38fea1b..99dfc3e649 100644 --- a/lib/faker/hacker.rb +++ b/lib/faker/hacker.rb @@ -1,4 +1,4 @@ -#Port of http://shinytoylabs.com/jargon/ +# Port of http://shinytoylabs.com/jargon/ module Faker class Hacker < Base flexible :hacker @@ -29,17 +29,15 @@ def ingverb end def 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}!".capitalize, - "I'll #{verb} the #{adjective} #{abbreviation} #{noun}, that should #{noun} the #{abbreviation} #{noun}!" - ] + ["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}!".capitalize, + "I'll #{verb} the #{adjective} #{abbreviation} #{noun}, that should #{noun} the #{abbreviation} #{noun}!"] end end - end end diff --git a/lib/faker/hipster.rb b/lib/faker/hipster.rb index 0757d1c9c9..78e6d34d08 100644 --- a/lib/faker/hipster.rb +++ b/lib/faker/hipster.rb @@ -3,7 +3,7 @@ class Hipster < Base class << self def word random_word = sample(translate('faker.hipster.words')) - random_word.match(/\s/) ? word : random_word + random_word =~ /\s/ ? word : random_word end def words(num = 3, supplemental = false, spaces_allowed = false) @@ -12,11 +12,11 @@ def words(num = 3, supplemental = false, spaces_allowed = false) translate('faker.hipster.words') + (supplemental ? translate('faker.lorem.words') : []) ) - word_list = word_list * ((resolved_num / word_list.length) + 1) + word_list *= ((resolved_num / word_list.length) + 1) return shuffle(word_list)[0, resolved_num] if spaces_allowed words = shuffle(word_list)[0, resolved_num] - words.each_with_index { |w, i| words[i] = word if w.match(/\s/) } + words.each_with_index { |w, i| words[i] = word if w =~ /\s/ } end def sentence(word_count = 4, supplemental = false, random_words_to_add = 6) @@ -43,7 +43,7 @@ def paragraphs(paragraph_count = 3, supplemental = false) end end - private + private # If an array or range is passed, a random value will be selected. # All other values are simply returned. diff --git a/lib/faker/id_number.rb b/lib/faker/id_number.rb index 796dff65ef..39eba247e1 100644 --- a/lib/faker/id_number.rb +++ b/lib/faker/id_number.rb @@ -1,16 +1,14 @@ module Faker class IDNumber < Base - INVALID_SSN = [ - /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}/ - ] + /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}/ + ].freeze class << self - def valid _translate('valid') end @@ -31,6 +29,5 @@ def _translate(key) parse("id_number.#{key}") end end - end end diff --git a/lib/faker/internet.rb b/lib/faker/internet.rb index 47d68ba87e..57b843fe38 100644 --- a/lib/faker/internet.rb +++ b/lib/faker/internet.rb @@ -1,7 +1,6 @@ module Faker class Internet < Base class << self - def email(name = nil) [user_name(name), domain_name].join('@') end @@ -11,37 +10,40 @@ def free_email(name = nil) end def safe_email(name = nil) - [user_name(name), 'example.'+ sample(%w[org com net])].join('@') + [user_name(name), 'example.' + sample(%w[org com net])].join('@') end - def user_name(specifier = nil, separators = %w(. _)) + def user_name(specifier = nil, separators = %w[. _]) with_locale(:en) do - if specifier.respond_to?(:scan) - return shuffle(specifier.scan(/\w+/)).join(sample(separators)).downcase - elsif specifier.kind_of?(Integer) + return shuffle(specifier.scan(/\w+/)).join(sample(separators)).downcase if specifier.respond_to?(:scan) + if specifier.is_a?(Integer) # If specifier is Integer and has large value, Argument error exception is raised to overcome memory full error - raise ArgumentError, "Given argument is too large" if specifier > 10**6 + raise ArgumentError, 'Given argument is too large' if specifier > 10**6 tries = 0 # Don't try forever in case we get something like 1_000_000. - begin + result = nil + loop do result = user_name(nil, separators) tries += 1 - end while result.length < specifier && tries < 7 - return result * (specifier/result.length + 1) if specifier > 0 - elsif specifier.kind_of?(Range) + break unless result.length < specifier && tries < 7 + end + return result * (specifier / result.length + 1) if specifier > 0 + elsif specifier.is_a?(Range) tries = 0 - begin + result = nil + loop do result = user_name(specifier.min, separators) tries += 1 - end while !specifier.include?(result.length) && tries < 7 + break unless !specifier.include?(result.length) && tries < 7 + end return result[0...specifier.max] end sample([ - Char.prepare(Name.first_name), - [Name.first_name, Name.last_name].map{ |name| - Char.prepare(name) - }.join(sample(separators)) - ]) + Char.prepare(Name.first_name), + [Name.first_name, Name.last_name].map do |name| + Char.prepare(name) + end.join(sample(separators)) + ]) end end @@ -60,7 +62,7 @@ def password(min_length = 8, max_length = 16, mix_case = true, special_chars = f end if special_chars - chars = %w(! @ # $ % ^ & *) + chars = %w[! @ # $ % ^ & *] rand(1..min_length).times do |i| temp[i] = chars[rand(chars.length)] end @@ -73,7 +75,7 @@ def domain_name with_locale(:en) { [Char.prepare(domain_word), domain_suffix].join('.') } end - def fix_umlauts(string='') + def fix_umlauts(string = '') Char.fix_umlauts(string) end @@ -85,74 +87,78 @@ def domain_suffix fetch('internet.domain_suffix') end - def mac_address(prefix='') - prefix_digits = prefix.split(':').map{ |d| d.to_i(16) } - address_digits = (6 - prefix_digits.size).times.map{ rand(256) } - (prefix_digits + address_digits).map{ |d| '%02x' % d }.join(':') + def mac_address(prefix = '') + prefix_digits = prefix.split(':').map { |d| d.to_i(16) } + address_digits = Array.new((6 - prefix_digits.size)) { rand(256) } + (prefix_digits + address_digits).map { |d| format('%02x', d) }.join(':') end def ip_v4_address ary = (2..254).to_a - [ sample(ary), sample(ary), sample(ary), sample(ary) ].join('.') + [sample(ary), sample(ary), sample(ary), sample(ary)].join('.') end def private_ip_v4_address - begin + addr = nil + loop do addr = ip_v4_address - end while !private_net_checker[addr] + break if private_net_checker[addr] + end addr end def public_ip_v4_address - begin + addr = nil + loop do addr = ip_v4_address - end while reserved_net_checker[addr] + break unless reserved_net_checker[addr] + end addr end def private_nets_regex [ - /^10\./, # 10.0.0.0 – 10.255.255.255 - /^100\.(6[4-9]|[7-9]\d|1[0-1]\d|12[0-7])\./, # 100.64.0.0 – 100.127.255.255 - /^127\./, # 127.0.0.0 – 127.255.255.255 - /^169\.254\./, # 169.254.0.0 – 169.254.255.255 - /^172\.(1[6-9]|2\d|3[0-1])\./, # 172.16.0.0 – 172.31.255.255 - /^192\.0\.0\./, # 192.0.0.0 – 192.0.0.255 - /^192\.168\./, # 192.168.0.0 – 192.168.255.255 - /^198\.(1[8-9])\./ # 198.18.0.0 – 198.19.255.255 + /^10\./, # 10.0.0.0 - 10.255.255.255 + /^100\.(6[4-9]|[7-9]\d|1[0-1]\d|12[0-7])\./, # 100.64.0.0 - 100.127.255.255 + /^127\./, # 127.0.0.0 - 127.255.255.255 + /^169\.254\./, # 169.254.0.0 - 169.254.255.255 + /^172\.(1[6-9]|2\d|3[0-1])\./, # 172.16.0.0 - 172.31.255.255 + /^192\.0\.0\./, # 192.0.0.0 - 192.0.0.255 + /^192\.168\./, # 192.168.0.0 - 192.168.255.255 + /^198\.(1[8-9])\./ # 198.18.0.0 - 198.19.255.255 ] end def private_net_checker - lambda { |addr| private_nets_regex.any? { |net| net =~ addr } } + ->(addr) { private_nets_regex.any? { |net| net =~ addr } } end def reserved_nets_regex [ - /^0\./, # 0.0.0.0 – 0.255.255.255 - /^192\.0\.2\./, # 192.0.2.0 – 192.0.2.255 - /^192\.88\.99\./, # 192.88.99.0 – 192.88.99.255 - /^198\.51\.100\./, # 198.51.100.0 – 198.51.100.255 - /^203\.0\.113\./, # 203.0.113.0 – 203.0.113.255 - /^(22[4-9]|23\d)\./, # 224.0.0.0 – 239.255.255.255 - /^(24\d|25[0-5])\./ # 240.0.0.0 – 255.255.255.254 and 255.255.255.255 + /^0\./, # 0.0.0.0 - 0.255.255.255 + /^192\.0\.2\./, # 192.0.2.0 - 192.0.2.255 + /^192\.88\.99\./, # 192.88.99.0 - 192.88.99.255 + /^198\.51\.100\./, # 198.51.100.0 - 198.51.100.255 + /^203\.0\.113\./, # 203.0.113.0 - 203.0.113.255 + /^(22[4-9]|23\d)\./, # 224.0.0.0 - 239.255.255.255 + /^(24\d|25[0-5])\./ # 240.0.0.0 - 255.255.255.254 and 255.255.255.255 ] end def reserved_net_checker - ->(addr){ (private_nets_regex + reserved_nets_regex).any? { |net| net =~ addr } } + ->(addr) { (private_nets_regex + reserved_nets_regex).any? { |net| net =~ addr } } end def ip_v4_cidr - "#{ip_v4_address}/#{1 + rand(31)}" + "#{ip_v4_address}/#{rand(1..31)}" end def ip_v6_address - (1..8).map { rand(65536).to_s(16) }.join(':') + (1..8).map { rand(65_536).to_s(16) }.join(':') end def ip_v6_cidr - "#{ip_v6_address}/#{1 + rand(127)}" + "#{ip_v6_address}/#{rand(1..127)}" end def url(host = domain_name, path = "/#{user_name}", scheme = 'http') @@ -161,11 +167,11 @@ def url(host = domain_name, path = "/#{user_name}", scheme = 'http') def slug(words = nil, glue = nil) glue ||= sample(%w[- _ .]) - (words || Faker::Lorem::words(2).join(' ')).gsub(' ', glue).downcase + (words || Faker::Lorem.words(2).join(' ')).gsub(' ', glue).downcase end def device_token - shuffle(rand(16 ** 64).to_s(16).rjust(64, '0').chars.to_a).join + shuffle(rand(16**64).to_s(16).rjust(64, '0').chars.to_a).join end def user_agent(vendor = nil) diff --git a/lib/faker/job.rb b/lib/faker/job.rb index e5ac2d516a..891e64cfaa 100644 --- a/lib/faker/job.rb +++ b/lib/faker/job.rb @@ -3,14 +3,17 @@ class Job < Base flexible :job class << self - def title parse('job.title') end - def field; fetch('job.field'); end - def key_skill; fetch('job.key_skills'); end + def field + fetch('job.field') + end + def key_skill + fetch('job.key_skills') + end end end end diff --git a/lib/faker/lebowski.rb b/lib/faker/lebowski.rb index a879993f5b..aa76e9de3b 100644 --- a/lib/faker/lebowski.rb +++ b/lib/faker/lebowski.rb @@ -4,7 +4,7 @@ class << self def actor fetch('lebowski.actors') end - + def character fetch('lebowski.characters') end @@ -14,4 +14,4 @@ def quote end end end -end \ No newline at end of file +end diff --git a/lib/faker/lorem.rb b/lib/faker/lorem.rb index e8d3c6dbe9..ab99a2ae11 100644 --- a/lib/faker/lorem.rb +++ b/lib/faker/lorem.rb @@ -14,7 +14,7 @@ def words(num = 3, supplemental = false) translate('faker.lorem.words') + (supplemental ? translate('faker.lorem.supplemental') : []) ) - word_list = word_list * ((resolved_num / word_list.length) + 1) + word_list *= ((resolved_num / word_list.length) + 1) shuffle(word_list)[0, resolved_num] end @@ -52,7 +52,7 @@ def questions(question_count = 3, supplemental = false) 1.upto(resolve(question_count)).collect { question(3, supplemental) } end - private + private # If an array or range is passed, a random value will be selected. # All other values are simply returned. diff --git a/lib/faker/lorem_pixel.rb b/lib/faker/lorem_pixel.rb index 31078f2a09..5e23edf7ba 100644 --- a/lib/faker/lorem_pixel.rb +++ b/lib/faker/lorem_pixel.rb @@ -1,13 +1,26 @@ module Faker class LoremPixel < Base class << self - SUPPORTED_CATEGORIES = %w(abstract animals business cats city food nightlife fashion people nature sports technics transport) + SUPPORTED_CATEGORIES = %w[abstract + animals + business + cats + city + food + nightlife + fashion + people + nature + sports + technics + transport].freeze + # rubocop:disable Metrics/ParameterLists def image(size = '300x300', is_gray = false, category = nil, number = nil, text = nil, secure: true) - raise ArgumentError, 'Size should be specified in format 300x300' unless size.match(/^[0-9]+x[0-9]+$/) + raise ArgumentError, 'Size should be specified in format 300x300' unless size =~ /^[0-9]+x[0-9]+$/ raise ArgumentError, "Supported categories are #{SUPPORTED_CATEGORIES.join(', ')}" unless category.nil? || SUPPORTED_CATEGORIES.include?(category) raise ArgumentError, 'Category required when number is passed' if !number.nil? && category.nil? - raise ArgumentError, 'Number must be between 1 and 10' unless number.nil? || (1..10).include?(number) + raise ArgumentError, 'Number must be between 1 and 10' unless number.nil? || (1..10).cover?(number) raise ArgumentError, 'Category and number must be passed when text is passed' if !text.nil? && number.nil? && category.nil? url_parts = secure ? ['https:/'] : ['http:/'] @@ -17,6 +30,7 @@ def image(size = '300x300', is_gray = false, category = nil, number = nil, text url_parts += [category, number, text].compact url_parts.join('/') end + # rubocop:enable Metrics/ParameterLists end end end diff --git a/lib/faker/lovecraft.rb b/lib/faker/lovecraft.rb index f23f417f55..961d6d9d06 100644 --- a/lib/faker/lovecraft.rb +++ b/lib/faker/lovecraft.rb @@ -6,7 +6,7 @@ def location end def fhtagn(number_of = 1) - number_of.times.collect { fetch('lovecraft.fhtagn') }.join(". ") + Array.new(number_of) { fetch('lovecraft.fhtagn') }.join('. ') end def deity @@ -23,20 +23,19 @@ def sentence(word_count = 4, random_words_to_add = 6) def word random_word = sample(translate('faker.lovecraft.words')) - random_word.match(/\s/) ? word : random_word + random_word =~ /\s/ ? word : random_word end def words(num = 3, spaces_allowed = false) resolved_num = resolve(num) word_list = translate('faker.lovecraft.words') - word_list = word_list * ((resolved_num / word_list.length) + 1) + word_list *= ((resolved_num / word_list.length) + 1) return shuffle(word_list)[0, resolved_num] if spaces_allowed words = shuffle(word_list)[0, resolved_num] - words.each_with_index { |w, i| words[i] = word if w.match(/\s/) } + words.each_with_index { |w, i| words[i] = word if w =~ /\s/ } end - def sentences(sentence_count = 3) [].tap do |sentences| 1.upto(resolve(sentence_count)) do diff --git a/lib/faker/markdown.rb b/lib/faker/markdown.rb index ae22902a95..ae27f19b43 100644 --- a/lib/faker/markdown.rb +++ b/lib/faker/markdown.rb @@ -1,7 +1,6 @@ module Faker class Markdown < Base class << self - def headers "#{fetch('markdown.headers')} #{Lorem.word.capitalize}" end @@ -20,7 +19,7 @@ def ordered_list result = [] number.times do |i| - result << "#{i.to_s}. #{Faker::Lorem.sentence(1)} \n" + result << "#{i}. #{Faker::Lorem.sentence(1)} \n" end result.join('') end @@ -29,7 +28,7 @@ def unordered_list number = rand(1..10) result = [] - number.times do |i| + number.times do |_i| result << "* #{Faker::Lorem.sentence(1)} \n" end result.join('') @@ -61,7 +60,6 @@ def random def available_methods Markdown.public_methods(false) - Base.methods end - end end end diff --git a/lib/faker/measurement.rb b/lib/faker/measurement.rb index fb50aadc2b..bd9b7e6c38 100644 --- a/lib/faker/measurement.rb +++ b/lib/faker/measurement.rb @@ -1,8 +1,8 @@ module Faker class Measurement < Base class << self - ALL = "all" - NONE = "none" + ALL = 'all'.freeze + NONE = 'none'.freeze def height(amount = rand(10)) ensure_valid_amount(amount) @@ -11,7 +11,7 @@ def height(amount = rand(10)) elsif amount == NONE fetch('measurement.height') else - "#{amount.to_s} #{check_for_plural(fetch('measurement.height'), amount)}" + "#{amount} #{check_for_plural(fetch('measurement.height'), amount)}" end end @@ -22,7 +22,7 @@ def length(amount = rand(10)) elsif amount == NONE fetch('measurement.length') else - "#{amount.to_s} #{check_for_plural(fetch('measurement.length'), amount)}" + "#{amount} #{check_for_plural(fetch('measurement.length'), amount)}" end end @@ -33,7 +33,7 @@ def volume(amount = rand(10)) elsif amount == NONE fetch('measurement.volume') else - "#{amount.to_s} #{check_for_plural(fetch('measurement.volume'), amount)}" + "#{amount} #{check_for_plural(fetch('measurement.volume'), amount)}" end end @@ -44,7 +44,7 @@ def weight(amount = rand(10)) elsif amount == NONE fetch('measurement.weight') else - "#{amount.to_s} #{check_for_plural(fetch('measurement.weight'), amount)}" + "#{amount} #{check_for_plural(fetch('measurement.weight'), amount)}" end end @@ -55,7 +55,7 @@ def metric_height(amount = rand(10)) elsif amount == NONE fetch('measurement.height') else - "#{amount.to_s} #{check_for_plural(fetch('measurement.height'), amount)}" + "#{amount} #{check_for_plural(fetch('measurement.height'), amount)}" end end @@ -66,7 +66,7 @@ def metric_length(amount = rand(10)) elsif amount == NONE fetch('measurement.length') else - "#{amount.to_s} #{check_for_plural(fetch('measurement.length'), amount)}" + "#{amount} #{check_for_plural(fetch('measurement.length'), amount)}" end end @@ -77,7 +77,7 @@ def metric_volume(amount = rand(10)) elsif amount == NONE fetch('measurement.volume') else - "#{amount.to_s} #{check_for_plural(fetch('measurement.volume'), amount)}" + "#{amount} #{check_for_plural(fetch('measurement.volume'), amount)}" end end @@ -88,16 +88,14 @@ def metric_weight(amount = rand(10)) elsif amount == NONE fetch('measurement.weight') else - "#{amount.to_s} #{check_for_plural(fetch('measurement.weight'), amount)}" + "#{amount} #{check_for_plural(fetch('measurement.weight'), amount)}" end end private def ensure_valid_amount(amount) - unless amount == NONE || amount == ALL || amount.is_a?(Integer) || amount.is_a?(Float) - raise ArgumentError, 'invalid amount' - end + raise ArgumentError, 'invalid amount' unless amount == NONE || amount == ALL || amount.is_a?(Integer) || amount.is_a?(Float) end def check_for_plural(text, number) @@ -110,14 +108,14 @@ def check_for_plural(text, number) def make_plural(text) case text - when "foot" - "feet" - when "inch" - "inches" - when "fluid ounce" - "fluid ounces" - when "metric ton" - "metric tons" + when 'foot' + 'feet' + when 'inch' + 'inches' + when 'fluid ounce' + 'fluid ounces' + when 'metric ton' + 'metric tons' else "#{text}s" end diff --git a/lib/faker/michael_scott.rb b/lib/faker/michael_scott.rb index 21cc05b910..5a68c9fff8 100644 --- a/lib/faker/michael_scott.rb +++ b/lib/faker/michael_scott.rb @@ -6,4 +6,4 @@ def quote end end end -end \ No newline at end of file +end diff --git a/lib/faker/music.rb b/lib/faker/music.rb index 5c41901bc2..f2f135e261 100644 --- a/lib/faker/music.rb +++ b/lib/faker/music.rb @@ -14,7 +14,7 @@ def instrument end def keys - ['C', 'D', 'E', 'F', 'G', 'A', 'B'] + %w[C D E F G A B] end def key_variants diff --git a/lib/faker/name.rb b/lib/faker/name.rb index be88ba2a1e..4bf3b72c37 100644 --- a/lib/faker/name.rb +++ b/lib/faker/name.rb @@ -3,7 +3,6 @@ class Name < Base flexible :name class << self - def name parse('name.name') end @@ -34,8 +33,8 @@ def title "#{fetch('name.title.descriptor')} #{fetch('name.title.level')} #{fetch('name.title.job')}" end - def initials(character_count=3) - (0...character_count).map { (65 + rand(26)).chr }.join + def initials(character_count = 3) + (0...character_count).map { rand(65..90).chr }.join end def job_titles diff --git a/lib/faker/number.rb b/lib/faker/number.rb index f28ca25ddf..a7319226a2 100644 --- a/lib/faker/number.rb +++ b/lib/faker/number.rb @@ -1,7 +1,7 @@ module Faker class Number < Base class << self - def number(digits=10) + def number(digits = 10) num = '' if digits > 1 num = non_zero_digit @@ -10,11 +10,11 @@ def number(digits=10) num + leading_zero_number(digits) end - def leading_zero_number(digits=10) - (1..digits).collect {digit}.join + def leading_zero_number(digits = 10) + (1..digits).collect { digit }.join end - def decimal_part(digits=10) + def decimal_part(digits = 10) num = '' if digits > 1 num = non_zero_digit @@ -23,27 +23,27 @@ def decimal_part(digits=10) leading_zero_number(digits) + num end - def decimal(l_digits=5, r_digits=2) - l_d = self.number(l_digits) - r_d = self.decimal_part(r_digits) + def decimal(l_digits = 5, r_digits = 2) + l_d = number(l_digits) + r_d = decimal_part(r_digits) "#{l_d}.#{r_d}" end def non_zero_digit - (rand(9) + 1).to_s + rand(1..9).to_s end def digit rand(10).to_s end - def hexadecimal(digits=6) - hex = "" + def hexadecimal(digits = 6) + hex = '' digits.times { hex += rand(15).to_s(16) } hex end - def normal(mean=1, standard_deviation=1) + def normal(mean = 1, standard_deviation = 1) theta = 2 * Math::PI * rand rho = Math.sqrt(-2 * Math.log(1 - rand)) scale = standard_deviation * rho @@ -51,7 +51,7 @@ def normal(mean=1, standard_deviation=1) end def between(from = 1.00, to = 5000.00) - Faker::Base::rand_in_range(from, to) + Faker::Base.rand_in_range(from, to) end def positive(from = 1.00, to = 5000.00) diff --git a/lib/faker/omniauth.rb b/lib/faker/omniauth.rb index 94dfaf4a80..d1c43b9352 100644 --- a/lib/faker/omniauth.rb +++ b/lib/faker/omniauth.rb @@ -16,7 +16,7 @@ class << self def google(name: nil, email: nil, uid: Number.number(9)) auth = Omniauth.new(name: name, email: email) { - provider: "google_oauth2", + provider: 'google_oauth2', uid: uid, info: { name: auth.name, @@ -42,22 +42,22 @@ def google(name: nil, email: nil, uid: Number.number(9)) profile: "https://plus.google.com/#{uid}", picture: image, gender: gender, - birthday: Date.backward(36400).strftime("%Y-%m-%d"), - local: "en", + birthday: Date.backward(36_400).strftime('%Y-%m-%d'), + local: 'en', hd: "#{Company.name.downcase}.com" - }, + } }, id_info: { - "iss" => "accounts.google.com", - "at_hash" => Crypto.md5, - "email_verified" => "true", - "sub" => Number.number(28).to_s, - "azp" => "APP_ID", - "email" => auth.email, - "aud" => "APP_ID", - "iat" => Number.number(10), - "exp" => Time.forward.to_i.to_s, - "openid_id" => "https://www.google.com/accounts/o8/id?id=#{uid}" + 'iss' => 'accounts.google.com', + 'at_hash' => Crypto.md5, + 'email_verified' => 'true', + 'sub' => Number.number(28).to_s, + 'azp' => 'APP_ID', + 'email' => auth.email, + 'aud' => 'APP_ID', + 'iat' => Number.number(10), + 'exp' => Time.forward.to_i.to_s, + 'openid_id' => "https://www.google.com/accounts/o8/id?id=#{uid}" } } end @@ -66,7 +66,7 @@ def facebook(name: nil, email: nil, username: nil, uid: Number.number(7)) auth = Omniauth.new(name: name, email: email) username ||= "#{auth.first_name.downcase[0]}#{auth.last_name.downcase}" { - provider: "facebook", + provider: 'facebook', uid: uid, info: { email: auth.email, @@ -106,11 +106,11 @@ def facebook(name: nil, email: nil, username: nil, uid: Number.number(7)) def twitter(name: nil, nickname: nil, uid: Number.number(6)) auth = Omniauth.new(name: name) - nickname ||= auth.name.downcase.gsub(' ', '') + nickname ||= auth.name.downcase.delete(' ') location = city_state description = Lorem.sentence { - provider: "twitter", + provider: 'twitter', uid: uid, info: { nickname: nickname, @@ -128,7 +128,7 @@ def twitter(name: nil, nickname: nil, uid: Number.number(6)) secret: Crypto.md5 }, extra: { - access_token: "", + access_token: '', raw_info: { name: auth.name, listed_count: random_number_from_range(1..10), @@ -144,7 +144,7 @@ def twitter(name: nil, nickname: nil, uid: Number.number(6)) id: uid, profile_background_tile: random_boolean, profile_sidebar_fill_color: Color.hex_color, - followers_count: random_number_from_range(1..10000), + followers_count: random_number_from_range(1..10_000), default_profile_image: random_boolean, screen_name: '', following: random_boolean, @@ -153,14 +153,14 @@ def twitter(name: nil, nickname: nil, uid: Number.number(6)) favourites_count: random_number_from_range(1..10), profile_background_color: Color.hex_color, is_translator: random_boolean, - friends_count: random_number_from_range(1..10000), + friends_count: random_number_from_range(1..10_000), notifications: random_boolean, geo_enabled: random_boolean, profile_background_image_url: image, protected: random_boolean, description: description, profile_link_color: Color.hex_color, - created_at: Time.backward.strftime("%a %b %d %H:%M:%S %z %Y"), + created_at: Time.backward.strftime('%a %b %d %H:%M:%S %z %Y'), id_str: uid, profile_image_url_https: image, default_profile: random_boolean, @@ -188,53 +188,53 @@ def linkedin(name: nil, email: nil, uid: Number.number(6)) industry = Commerce.department url = "http://www.linkedin.com/in/#{first_name}#{last_name}" { - "provider" => "linkedin", - "uid" => uid, - "info" => { - "name" => auth.name, - "email" => auth.email, - "nickname" => auth.name, - "first_name" => auth.first_name, - "last_name" => auth.last_name, - "location" => location, - "description" => description, - "image" => image, - "phone" => PhoneNumber.phone_number, - "headline" => description, - "industry" => industry, - "urls" => { - "public_profile" => url + 'provider' => 'linkedin', + 'uid' => uid, + 'info' => { + 'name' => auth.name, + 'email' => auth.email, + 'nickname' => auth.name, + 'first_name' => auth.first_name, + 'last_name' => auth.last_name, + 'location' => location, + 'description' => description, + 'image' => image, + 'phone' => PhoneNumber.phone_number, + 'headline' => description, + 'industry' => industry, + 'urls' => { + 'public_profile' => url } }, - "credentials" => { - "token" => token, - "secret" => secret + 'credentials' => { + 'token' => token, + 'secret' => secret }, - "extra" => { - "access_token" => { - "token" => token, - "secret" => secret, - "consumer" => nil, - "params" => { + 'extra' => { + 'access_token' => { + 'token' => token, + 'secret' => secret, + 'consumer' => nil, + 'params' => { oauth_token: token, oauth_token_secret: secret, oauth_expires_in: Time.forward.to_i, - oauth_authorization_expires_in: Time.forward.to_i, + oauth_authorization_expires_in: Time.forward.to_i }, - "response" => nil + 'response' => nil }, - "raw_info" => { - "firstName" => auth.first_name, - "headline" => description, - "id" => uid, - "industry" => industry, - "lastName" => auth.last_name, - "location" => { - "country" => { "code" => Address.country_code.downcase }, - "name" => city_state.split(', ').first, + 'raw_info' => { + 'firstName' => auth.first_name, + 'headline' => description, + 'id' => uid, + 'industry' => industry, + 'lastName' => auth.last_name, + 'location' => { + 'country' => { 'code' => Address.country_code.downcase }, + 'name' => city_state.split(', ').first }, - "pictureUrl" => image, - "publicProfileUrl" => url + 'pictureUrl' => image, + 'publicProfileUrl' => url } } } @@ -242,18 +242,18 @@ def linkedin(name: nil, email: nil, uid: Number.number(6)) def github(name: nil, email: nil, uid: Number.number(8)) auth = Omniauth.new(name: name, email: email) - login = auth.name.downcase.gsub(' ','-') + login = auth.name.downcase.tr(' ', '-') html_url = "https://github.com/#{login}" api_url = "https://api.github.com/users/#{login}" { - provider: "github", + provider: 'github', uid: uid, info: { nickname: login, email: auth.email, name: auth.name, image: image, - urls:{ + urls: { GitHub: html_url } }, @@ -266,7 +266,7 @@ def github(name: nil, email: nil, uid: Number.number(8)) login: login, id: uid, avatar_url: image, - gravatar_id: "", + gravatar_id: '', url: api_url, html_url: html_url, followers_url: "#{api_url}/followers", @@ -278,7 +278,7 @@ def github(name: nil, email: nil, uid: Number.number(8)) repos_url: "#{api_url}/repos", events_url: "#{api_url}/events{/privacy}", received_events_url: "#{api_url}/received_events", - type: "User", + type: 'User', site_admin: random_boolean, name: auth.name, company: nil, @@ -291,7 +291,7 @@ def github(name: nil, email: nil, uid: Number.number(8)) public_gists: random_number_from_range(1..1000), followers: random_number_from_range(1..1000), following: random_number_from_range(1..1000), - created_at: Time.backward(36400).iso8601, + created_at: Time.backward(36_400).iso8601, updated_at: Time.backward(2).iso8601 } } @@ -300,29 +300,29 @@ def github(name: nil, email: nil, uid: Number.number(8)) private - def gender - shuffle(["male", "female"]).pop - end + def gender + shuffle(%w[male female]).pop + end - def timezone - shuffle((-12..12).to_a).pop - end + def timezone + shuffle((-12..12).to_a).pop + end - def image - Placeholdit.image - end + def image + Placeholdit.image + end - def city_state - "#{Address.city}, #{Address.state}" - end + def city_state + "#{Address.city}, #{Address.state}" + end - def random_number_from_range(range) - shuffle(range.to_a).pop - end + def random_number_from_range(range) + shuffle(range.to_a).pop + end - def random_boolean - shuffle([true, false]).pop - end + def random_boolean + shuffle([true, false]).pop + end end end end diff --git a/lib/faker/phone_number.rb b/lib/faker/phone_number.rb index 689f39dbdf..ddedfe56de 100644 --- a/lib/faker/phone_number.rb +++ b/lib/faker/phone_number.rb @@ -11,34 +11,28 @@ def cell_phone # US and Canada only def area_code - begin - fetch('phone_number.area_code') - rescue I18n::MissingTranslationData - nil - end + fetch('phone_number.area_code') + rescue I18n::MissingTranslationData + nil end # US and Canada only def exchange_code - begin - fetch('phone_number.exchange_code') - rescue I18n::MissingTranslationData - nil - end + fetch('phone_number.exchange_code') + rescue I18n::MissingTranslationData + nil end # US and Canada only # Can be used for both extensions and last four digits of phone number. # Since extensions can be of variable length, this method taks a length parameter def subscriber_number(length = 4) - begin - rand.to_s[2..(1 + length)] - rescue I18n::MissingTranslationData - nil - end + rand.to_s[2..(1 + length)] + rescue I18n::MissingTranslationData + nil end - alias_method :extension, :subscriber_number + alias extension subscriber_number end end end diff --git a/lib/faker/placeholdit.rb b/lib/faker/placeholdit.rb index b0c6eb2474..fdaa25beea 100644 --- a/lib/faker/placeholdit.rb +++ b/lib/faker/placeholdit.rb @@ -1,10 +1,10 @@ module Faker class Placeholdit < Base class << self - SUPPORTED_FORMATS = %w(png jpg gif jpeg) + SUPPORTED_FORMATS = %w[png jpg gif jpeg].freeze def image(size = '300x300', format = 'png', background_color = nil, text_color = nil, text = nil) - raise ArgumentError, "Size should be specified in format 300x300" unless size.match(/^[0-9]+x[0-9]+$/) + raise ArgumentError, 'Size should be specified in format 300x300' unless size =~ /^[0-9]+x[0-9]+$/ raise ArgumentError, "Supported formats are #{SUPPORTED_FORMATS.join(', ')}" unless SUPPORTED_FORMATS.include?(format) raise ArgumentError, "background_color must be a hex value without '#'" unless background_color.nil? || background_color.match(/((?:^\h{3}$)|(?:^\h{6}$)){1}(?!.*\H)/) raise ArgumentError, "text_color must be a hex value without '#'" unless text_color.nil? || text_color.match(/((?:^\h{3}$)|(?:^\h{6}$)){1}(?!.*\H)/) diff --git a/lib/faker/rick_and_morty.rb b/lib/faker/rick_and_morty.rb index e8512b9eaa..7cbea59481 100644 --- a/lib/faker/rick_and_morty.rb +++ b/lib/faker/rick_and_morty.rb @@ -14,4 +14,4 @@ def quote end end end -end \ No newline at end of file +end diff --git a/lib/faker/science.rb b/lib/faker/science.rb index 7c3bc65d2e..744c01c430 100644 --- a/lib/faker/science.rb +++ b/lib/faker/science.rb @@ -1,7 +1,6 @@ module Faker class Science < Base class << self - def element fetch('science.element') end @@ -9,7 +8,6 @@ def element def scientist fetch('science.scientist') end - end end end diff --git a/lib/faker/seinfeld.rb b/lib/faker/seinfeld.rb index 137c79a392..775fd62a8e 100644 --- a/lib/faker/seinfeld.rb +++ b/lib/faker/seinfeld.rb @@ -8,6 +8,6 @@ def character def quote fetch('seinfeld.quote') end - end + end end end diff --git a/lib/faker/shakespeare.rb b/lib/faker/shakespeare.rb index 993fac39f9..8bd43a7049 100644 --- a/lib/faker/shakespeare.rb +++ b/lib/faker/shakespeare.rb @@ -1,7 +1,6 @@ module Faker class Shakespeare < Base class << self - def hamlet_quote sample(hamlet) end @@ -26,7 +25,6 @@ def as_you_like_it fetch('shakespeare.as_you_like_it') end - def king_richard_iii fetch('shakespeare.king_richard_iii') end @@ -34,7 +32,6 @@ def king_richard_iii def romeo_and_juliet fetch('shakespeare.romeo_and_juliet') end - end end end diff --git a/lib/faker/simpsons.rb b/lib/faker/simpsons.rb index 5641e43e46..5fcdaf1197 100644 --- a/lib/faker/simpsons.rb +++ b/lib/faker/simpsons.rb @@ -1,10 +1,7 @@ -#encoding: utf-8 -#frozen_string_literal: true +# frozen_string_literal: true module Faker - class Simpsons < Base - def self.character fetch('simpsons.characters') end @@ -16,7 +13,5 @@ def self.location def self.quote fetch('simpsons.quotes') end - - end #class Simpsons - -end #module Faker + end +end diff --git a/lib/faker/slack_emoji.rb b/lib/faker/slack_emoji.rb index e6c5285b2d..52d55a76b7 100644 --- a/lib/faker/slack_emoji.rb +++ b/lib/faker/slack_emoji.rb @@ -1,7 +1,6 @@ module Faker class SlackEmoji < Base class << self - def people fetch('slack_emoji.people') end @@ -37,7 +36,6 @@ def custom def emoji parse('slack_emoji.emoji') end - end end end diff --git a/lib/faker/star_trek.rb b/lib/faker/star_trek.rb index 6cc36343d1..0745651a94 100644 --- a/lib/faker/star_trek.rb +++ b/lib/faker/star_trek.rb @@ -12,10 +12,10 @@ def location def specie fetch('star_trek.specie') end - + def villain fetch('star_trek.villain') end end end -end \ No newline at end of file +end diff --git a/lib/faker/star_wars.rb b/lib/faker/star_wars.rb index 6773129d96..f2db5a7d4e 100644 --- a/lib/faker/star_wars.rb +++ b/lib/faker/star_wars.rb @@ -36,9 +36,9 @@ def vehicle def wookiee_sentence sentence = sample(wookiee_words).capitalize - rand(0..10).times { sentence += " " + sample(wookiee_words)} + rand(0..10).times { sentence += ' ' + sample(wookiee_words) } - sentence + sample(['.','?','!']) + sentence + sample(['.', '?', '!']) end def call_numbers @@ -94,9 +94,8 @@ def wookiee_words fetch_all('star_wars.wookiee_words') end - alias_method :wookie_sentence, :wookiee_sentence - alias_method :wookie_words, :wookiee_words - + alias wookie_sentence wookiee_sentence + alias wookie_words wookiee_words end end end diff --git a/lib/faker/string.rb b/lib/faker/string.rb index 1f34046e4c..f394daf7f4 100644 --- a/lib/faker/string.rb +++ b/lib/faker/string.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + module Faker class String < Base class << self @@ -6,7 +7,7 @@ def random(length = 32) utf8string select_a length end - private + private def select_a(length) if length.class.included_modules.include? Enumerable @@ -24,20 +25,20 @@ def utf8string(length) end def space_or_utf8_char(ratio) - sample [ 32.chr(Encoding::UTF_8), [utf8character]* ratio ].flatten + sample [32.chr(Encoding::UTF_8), [utf8character] * ratio].flatten end def char_space_ratio - sample [ 2, [3]*5, [5]*17, [7]*11, 11, 191, ].flatten + sample [2, [3] * 5, [5] * 17, [7] * 11, 11, 191].flatten end def utf8character sample([ - rand(59)+ 32, # latin alphabet - rand(128), # 7-bit ASCII - rand(0xd800), # utf-8 codepoints below utf-16 surrogate halves - rand(0x102000)+ 0xe000 # utf-8 codepoints above utf-16 surrogate halves - ]).chr(Encoding::UTF_8) + rand(32..90), # latin alphabet + rand(128), # 7-bit ASCII + rand(0xd800), # utf-8 codepoints below utf-16 surrogate halves + rand(57_344..1_114_111) # utf-8 codepoints above utf-16 surrogate halves + ]).chr(Encoding::UTF_8) end end end diff --git a/lib/faker/stripe.rb b/lib/faker/stripe.rb index 29580a792b..8ddcc3d3ea 100644 --- a/lib/faker/stripe.rb +++ b/lib/faker/stripe.rb @@ -9,11 +9,11 @@ def valid_card(card_type = nil) else unless valid_cards.include?(card_type.to_sym) raise ArgumentError, - "Valid credit cards argument can be left blank or include #{valid_cards.join(', ')}" + "Valid credit cards argument can be left blank or include #{valid_cards.join(', ')}" end end - return fetch('stripe.valid_cards.' + card_type) + fetch('stripe.valid_cards.' + card_type) end def invalid_card(card_error = nil) @@ -24,15 +24,15 @@ def invalid_card(card_error = nil) else unless invalid_cards.include?(card_error.to_sym) raise ArgumentError, - "Invalid credit cards argument can be left blank or include #{invalid_cards.join(', ')}" + "Invalid credit cards argument can be left blank or include #{invalid_cards.join(', ')}" end end - return fetch('stripe.invalid_cards.' + card_error) + fetch('stripe.invalid_cards.' + card_error) end def month - "%02d" % rand_in_range(1, 12) + format('%02d', rand_in_range(1, 12)) end def year @@ -41,9 +41,8 @@ def year end def ccv(card_type = nil) - (card_type.to_s == "amex" ? rand_in_range(1000, 9999) : rand_in_range(100, 999)).to_s + (card_type.to_s == 'amex' ? rand_in_range(1000, 9999) : rand_in_range(100, 999)).to_s end - end end end diff --git a/lib/faker/team.rb b/lib/faker/team.rb index a24b030428..df3ff74ed9 100644 --- a/lib/faker/team.rb +++ b/lib/faker/team.rb @@ -19,6 +19,5 @@ def mascot fetch('team.mascot') end end - end end diff --git a/lib/faker/time.rb b/lib/faker/time.rb index cf722a3728..658ec1ca19 100755 --- a/lib/faker/time.rb +++ b/lib/faker/time.rb @@ -1,14 +1,14 @@ module Faker class Time < Faker::Date TIME_RANGES = { - :all => (0..23), - :day => (9..17), - :night => (18..23), - :morning => (6..11), - :afternoon => (12..17), - :evening => (17..21), - :midnight => (0..4) - } + all: (0..23), + day: (9..17), + night: (18..23), + morning: (6..11), + afternoon: (12..17), + evening: (17..21), + midnight: (0..4) + }.freeze class << self def between(from, to, period = :all, format = nil) @@ -31,11 +31,11 @@ def date_with_random_time(date, period) end def time_with_format(time, format) - format.nil? ? time : I18n.l( DateTime.parse(time.to_s), :format => format ) + format.nil? ? time : I18n.l(DateTime.parse(time.to_s), format: format) end def hours(period) - raise ArgumentError, 'invalid period' unless TIME_RANGES.has_key? period + raise ArgumentError, 'invalid period' unless TIME_RANGES.key? period sample(TIME_RANGES[period].to_a) end diff --git a/lib/faker/twin_peaks.rb b/lib/faker/twin_peaks.rb index 4e46bae447..e420ef8a45 100644 --- a/lib/faker/twin_peaks.rb +++ b/lib/faker/twin_peaks.rb @@ -4,11 +4,11 @@ class << self def character fetch('twin_peaks.characters') end - + def location fetch('twin_peaks.locations') end - + def quote fetch('twin_peaks.quotes') end diff --git a/lib/faker/types.rb b/lib/faker/types.rb index 92dba29717..6d2d1bf9ed 100644 --- a/lib/faker/types.rb +++ b/lib/faker/types.rb @@ -1,47 +1,47 @@ module Faker class Types < Base CHARACTERS = ('0'..'9').to_a + ('a'..'z').to_a - SIMPLE_TYPES = [:string, :fixnum] - COMPLEX_TYPES = [:hash, :array] + SIMPLE_TYPES = %i[string fixnum].freeze + COMPLEX_TYPES = %i[hash array].freeze class << self - def string(words=1) + def string(words = 1) resolved_num = resolve(words) - word_list = ( + word_list = translate('faker.lorem.words') - ) - word_list = word_list * ((resolved_num / word_list.length) + 1) - shuffle(word_list)[0, resolved_num].join(" ") + + word_list *= ((resolved_num / word_list.length) + 1) + shuffle(word_list)[0, resolved_num].join(' ') end def character sample(CHARACTERS) end - def integer(from=0, to=100) + def integer(from = 0, to = 100) rand(from..to).to_i end - def hash(key_count=1) - Hash.new.tap do |hsh| + def hash(key_count = 1) + {}.tap do |hsh| Lorem.words(key_count * 2).uniq.first(key_count).each do |s| - hsh.merge!({s.to_sym => self.random_type}) + hsh.merge!(s.to_sym => random_type) end end end - def complex_hash(key_count=1) - Hash.new.tap do |hsh| + def complex_hash(key_count = 1) + {}.tap do |hsh| Lorem.words(key_count * 2).uniq.first(key_count).each do |s| - hsh.merge!({s.to_sym => self.random_complex_type}) + hsh.merge!(s.to_sym => random_complex_type) end end end - def array(len=1) - Array.new.tap do |ar| + def array(len = 1) + [].tap do |ar| len.times do - ar.push self.random_type + ar.push random_type end end end @@ -50,11 +50,11 @@ def random_type type_to_use = SIMPLE_TYPES[rand(0..SIMPLE_TYPES.length - 1)] case type_to_use when :string - self.string + string when :fixnum - self.integer + integer else - self.integer + integer end end @@ -63,15 +63,15 @@ def random_complex_type type_to_use = types[rand(0..types.length - 1)] case type_to_use when :string - self.string + string when :fixnum - self.integer + integer when :hash - self.hash + hash when :array - self.array + array else - self.integer + integer end end diff --git a/lib/faker/university.rb b/lib/faker/university.rb index c8aa07ce22..9941a9de70 100644 --- a/lib/faker/university.rb +++ b/lib/faker/university.rb @@ -16,12 +16,12 @@ def suffix end def greek_organization - 3.times.map { |_| sample(greek_alphabet) }.join + Array.new(3) { |_| sample(greek_alphabet) }.join end def greek_alphabet - ['Α', 'B', 'Γ', 'Δ', 'E', 'Z', 'H', 'Θ', 'I', 'K', 'Λ', 'M', 'N', 'Ξ', - 'O', 'Π', 'P', 'Σ', 'T', 'Y', 'Φ', 'X', 'Ψ', 'Ω'] + %w[Α B Γ Δ E Z H Θ I K Λ M N Ξ + O Π P Σ T Y Φ X Ψ Ω] end end end diff --git a/lib/faker/vehicle.rb b/lib/faker/vehicle.rb index 3b0cf13b4d..acbb1a01cd 100644 --- a/lib/faker/vehicle.rb +++ b/lib/faker/vehicle.rb @@ -2,17 +2,17 @@ module Faker class Vehicle < Base flexible :vehicle - VIN_CHARS = '0123456789.ABCDEFGH..JKLMN.P.R..STUVWXYZ' - VIN_MAP = '0123456789X' - VIN_WEIGHTS = '8765432X098765432' + VIN_CHARS = '0123456789.ABCDEFGH..JKLMN.P.R..STUVWXYZ'.freeze + VIN_MAP = '0123456789X'.freeze + VIN_WEIGHTS = '8765432X098765432'.freeze class << self - #ISO 3779 + # ISO 3779 def vin _, wmi, wmi_ext = sample(fetch_all('vehicle.manufacture')) - c = VIN_CHARS.split('').reject{ |n| n == '.'} - vehicle_identification_number = wmi.split('').concat( Array.new(14) { sample(c) } ) + c = VIN_CHARS.split('').reject { |n| n == '.' } + vehicle_identification_number = wmi.split('').concat(Array.new(14) { sample(c) }) (12..14).to_a.each_with_index { |n, i| vehicle_identification_number[n] = wmi_ext[i] } unless wmi_ext.nil? vehicle_identification_number[10] = fetch('vehicle.year') vehicle_identification_number[8] = vin_checksum(vehicle_identification_number) @@ -24,16 +24,15 @@ def manufacture sample(fetch_all('vehicle.manufacture')).first end - private + private - def calculate_vin_weight(character, i) - (VIN_CHARS.index(character) % 10) * VIN_MAP.index(VIN_WEIGHTS[i]) + def calculate_vin_weight(character, idx) + (VIN_CHARS.index(character) % 10) * VIN_MAP.index(VIN_WEIGHTS[idx]) end def vin_checksum(vehicle_identification_number) VIN_MAP[vehicle_identification_number.each_with_index.map(&method(:calculate_vin_weight)).inject(:+) % 11] end - end end end diff --git a/lib/faker/verb.rb b/lib/faker/verb.rb index cfef042858..2ebbc6fbf6 100644 --- a/lib/faker/verb.rb +++ b/lib/faker/verb.rb @@ -16,7 +16,7 @@ def past_participle def simple_present fetch('verbs.simple_present') end - + def ing_form fetch('verbs.ing_form') end diff --git a/lib/faker/version.rb b/lib/faker/version.rb index db48b847f1..2a9ebe8f9a 100644 --- a/lib/faker/version.rb +++ b/lib/faker/version.rb @@ -1,3 +1,3 @@ module Faker #:nodoc: - VERSION = "1.8.7" + VERSION = '1.8.7'.freeze end diff --git a/lib/helpers/char.rb b/lib/helpers/char.rb index 9c010d7668..19efa9a972 100644 --- a/lib/helpers/char.rb +++ b/lib/helpers/char.rb @@ -1,4 +1,4 @@ -# coding: utf-8 + module Faker module Char def self.prepare(string) @@ -10,16 +10,16 @@ def self.prepare(string) def self.fix_umlauts(string) string.gsub(/[äöüß]/i) do |match| case match.downcase - when "ä" 'ae' - when "ö" 'oe' - when "ü" 'ue' - when "ß" 'ss' + when 'ä' then 'ae' + when 'ö' then 'oe' + when 'ü' then 'ue' + when 'ß' then 'ss' end end end def self.romanize_cyrillic(string) - if Faker::Config.locale == "uk" + if Faker::Config.locale == 'uk' # Based on conventions abopted by BGN/PCGN for Ukrainian uk_chars = { 'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'h', 'ґ' => 'g', 'д' => 'd', @@ -39,22 +39,22 @@ def self.romanize_cyrillic(string) return string.gsub(/[а-яА-ЯіїєґІЇЄҐ]/, uk_chars) end - if Faker::Config.locale == "ru" + if Faker::Config.locale == 'ru' # Based on conventions abopted by BGN/PCGN for Russian ru_chars = { - 'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'h', 'д' => 'd', 'е' => 'e', - 'ё' => 'ye', 'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'й' => 'y', 'к' => 'k', - 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', - 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'kh', 'ц' => 'ts', - 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'shch', 'ы' => 'у', 'э' => 'e', 'ю' => 'yu', - 'я' => 'ya', - 'А' => 'a', 'Б' => 'b', 'В' => 'v', 'Г' => 'h', 'Д' => 'd', 'Е' => 'e', - 'Ё' => 'ye', 'Ж' => 'zh', 'З' => 'z', 'И' => 'i', 'Й' => 'y', 'К' => 'k', - 'Л' => 'l', 'М' => 'm', 'Н' => 'n', 'О' => 'o', 'П' => 'p', 'Р' => 'r', - 'С' => 's', 'Т' => 't', 'У' => 'u', 'Ф' => 'f', 'Х' => 'kh', 'Ц' => 'ts', - 'Ч' => 'ch', 'Ш' => 'sh', 'Щ' => 'shch', 'Ы' => 'у', 'Э' => 'e', 'Ю' => 'yu', - 'Я' => 'ya', - 'ь' => '', 'ъ' => '' # Ignore symbols, because its standard presentation is not allowed in URLs + 'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'h', 'д' => 'd', 'е' => 'e', + 'ё' => 'ye', 'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'й' => 'y', 'к' => 'k', + 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', + 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'kh', 'ц' => 'ts', + 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'shch', 'ы' => 'у', 'э' => 'e', 'ю' => 'yu', + 'я' => 'ya', + 'А' => 'a', 'Б' => 'b', 'В' => 'v', 'Г' => 'h', 'Д' => 'd', 'Е' => 'e', + 'Ё' => 'ye', 'Ж' => 'zh', 'З' => 'z', 'И' => 'i', 'Й' => 'y', 'К' => 'k', + 'Л' => 'l', 'М' => 'm', 'Н' => 'n', 'О' => 'o', 'П' => 'p', 'Р' => 'r', + 'С' => 's', 'Т' => 't', 'У' => 'u', 'Ф' => 'f', 'Х' => 'kh', 'Ц' => 'ts', + 'Ч' => 'ch', 'Ш' => 'sh', 'Щ' => 'shch', 'Ы' => 'у', 'Э' => 'e', 'Ю' => 'yu', + 'Я' => 'ya', + 'ь' => '', 'ъ' => '' # Ignore symbols, because its standard presentation is not allowed in URLs } return string.gsub(/[а-яА-Я]/, ru_chars) end diff --git a/lib/helpers/unique_generator.rb b/lib/helpers/unique_generator.rb index cec47be4fc..35ea0f2772 100644 --- a/lib/helpers/unique_generator.rb +++ b/lib/helpers/unique_generator.rb @@ -6,6 +6,7 @@ def initialize(generator, max_retries) @previous_results = Hash.new { |hash, key| hash[key] = Set.new } end + # rubocop:disable Style/MethodMissing def method_missing(name, *arguments) @max_retries.times do result = @generator.public_send(name, *arguments) @@ -18,6 +19,11 @@ def method_missing(name, *arguments) raise RetryLimitExceeded end + # rubocop:enable Style/MethodMissing + + def respond_to_missing?(method_name, include_private = false) + method_name.to_s.start_with?('faker_') || super + end RetryLimitExceeded = Class.new(StandardError) diff --git a/script/destroy b/script/destroy index 5fa7e10e71..97d99e9921 100755 --- a/script/destroy +++ b/script/destroy @@ -10,5 +10,5 @@ end require 'rubigen/scripts/destroy' ARGV.shift if ['--help', '-h'].include?(ARGV[0]) -RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit] +RubiGen::Base.use_component_sources! %i[rubygems newgem newgem_theme test_unit] RubiGen::Scripts::Destroy.new.run(ARGV) diff --git a/script/generate b/script/generate index 230a186856..b4ddfdf4ae 100755 --- a/script/generate +++ b/script/generate @@ -10,5 +10,5 @@ end require 'rubigen/scripts/generate' ARGV.shift if ['--help', '-h'].include?(ARGV[0]) -RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit] +RubiGen::Base.use_component_sources! %i[rubygems newgem newgem_theme test_unit] RubiGen::Scripts::Generate.new.run(ARGV) diff --git a/script/txt2html b/script/txt2html index 9da3e23bf6..c04abe574e 100755 --- a/script/txt2html +++ b/script/txt2html @@ -19,33 +19,36 @@ download = 'http://rubyforge.org/projects/faker' class Fixnum def ordinal # teens - return 'th' if (10..19).include?(self % 100) + return 'th' if (10..19).cover?(self % 100) # others case self % 10 - when 1: return 'st' - when 2: return 'nd' - when 3: return 'rd' - else return 'th' + when 1 + return 'st' + when 2 + return 'nd' + when 3 + return 'rd' end + 'th' end end class Time def pretty - return "#{mday}#{mday.ordinal} #{strftime('%B')} #{year}" + "#{mday}#{mday.ordinal} #{strftime('%B')} #{year}" end end def convert_syntax(syntax, source) - return Syntax::Convertors::HTML.for_syntax(syntax).convert(source).gsub(%r!^
|
$!,'') + Syntax::Convertors::HTML.for_syntax(syntax).convert(source).gsub(%r{^
|
$}, '') end if ARGV.length >= 1 src, template = ARGV template ||= File.join(File.dirname(__FILE__), '/../website/template.rhtml') - + else - puts("Usage: #{File.split($0).last} source.txt [template.rhtml] > output.html") + puts("Usage: #{File.split($PROGRAM_NAME).last} source.txt [template.rhtml] > output.html") exit! end @@ -57,15 +60,17 @@ File.open(src) do |fsrc| title_text = fsrc.readline body_text = fsrc.read syntax_items = [] - body_text.gsub!(%r!<(pre|code)[^>]*?syntax=['"]([^'"]+)[^>]*>(.*?)!m){ + body_text.gsub!(%r{<(pre|code)[^>]*?syntax=['"]([^'"]+)[^>]*>(.*?)}m) do ident = syntax_items.length - element, syntax, source = $1, $2, $3 + element = Regexp.last_match(1) + syntax = Regexp.last_match(2) + source = Regexp.last_match(3) syntax_items << "<#{element} class='syntax'>#{convert_syntax(syntax, source)}" "syntax-temp-#{ident}" - } - title = RedCloth.new(title_text).to_html.gsub(%r!<.*?>!,'').strip + end + title = RedCloth.new(title_text).to_html.gsub(/<.*?>/, '').strip body = RedCloth.new(body_text).to_html - body.gsub!(%r!(?:
)?syntax-temp-(\d+)(?:
)?!){ syntax_items[$1.to_i] } + body.gsub!(%r{(?:
)?syntax-temp-(\d+)(?:
)?}) { syntax_items[Regexp.last_match(1).to_i] } end stat = File.stat(src) created = stat.ctime diff --git a/tasks/test.rake b/tasks/test.rake index 217217f699..eda89c3211 100644 --- a/tasks/test.rake +++ b/tasks/test.rake @@ -1,11 +1,11 @@ require 'rake/testtask' Rake::TestTask.new do |t| - t.libs << "test" - t.libs << "." + t.libs << 'test' + t.libs << '.' t.test_files = FileList['test/test*.rb'] t.verbose = true t.warning = true end -task :default => :test +task default: :test diff --git a/tasks/website.rake b/tasks/website.rake index 5b0960b8d2..667e078b3c 100644 --- a/tasks/website.rake +++ b/tasks/website.rake @@ -1,16 +1,16 @@ desc 'Generate website files' task :website_generate do (Dir['website/**/*.txt'] - Dir['website/version*.txt']).each do |txt| - sh %{ ./script/txt2html #{txt} > #{txt.gsub(/txt$/,'html')} } + sh %( ./script/txt2html #{txt} > #{txt.gsub(/txt$/, 'html')} ) end end desc 'Upload website files to rubyforge' task :website_upload do - remote_dir = "/var/www/gforge-projects/faker/" + remote_dir = '/var/www/gforge-projects/faker/' local_dir = 'website' - sh %{rsync -acCv #{local_dir}/ #{ENV['USER']}@rubyforge.org:#{remote_dir}} + sh %(rsync -acCv #{local_dir}/ #{ENV['USER']}@rubyforge.org:#{remote_dir}) end desc 'Generate and upload website files' -task :website => [:website_generate, :website_upload, :publish_docs] +task website: %i[website_generate website_upload publish_docs] diff --git a/test/test_array_sample_method_compat.rb b/test/test_array_sample_method_compat.rb index e0dd74ec85..c1cf1e69e1 100644 --- a/test/test_array_sample_method_compat.rb +++ b/test/test_array_sample_method_compat.rb @@ -5,7 +5,6 @@ # behaves as the built-in Array#sample method from Ruby 1.9 or greater. # Under Ruby 1.9, they simply use the built-in Array#sample method class TestArraySampleMethodCompatibility < Test::Unit::TestCase - def test_returns_nil_or_empty_array_with_empty_source source = [] @@ -17,19 +16,19 @@ def test_returns_nil_or_empty_array_with_empty_source end def test_returns_one_array_elem_without_param - source = ['foo', 'bar'] + source = %w[foo bar] result = source.sample assert source.include? result end def test_returns_empty_array_with_param_zero - source = ['foo', 'bar'] + source = %w[foo bar] result = source.sample(0) assert_equal result, [] end def test_returns_an_array_with_integer_param - source = ['foo', 'bar', 'baz'] + source = %w[foo bar baz] result = source.sample(2) assert result.is_a? Array assert result.length == 2 @@ -37,18 +36,18 @@ def test_returns_an_array_with_integer_param end def test_returns_source_array_with_integer_param_equal_or_bigger_than_source_length - source = ['foo','bar'] + source = %w[foo bar] result = source.sample(2) assert result.is_a? Array - assert((source.sort <=> result.sort) == 0) + assert((source.sort <=> result.sort).zero?) result = source.sample(3) assert result.is_a? Array - assert((source.sort <=> result.sort) == 0) + assert((source.sort <=> result.sort).zero?) end - def test_raises_Argument_Error_with_negative_param - source = ['foo','bar'] + def test_raises_argument_error_with_negative_param + source = %w[foo bar] assert_raise ArgumentError do source.sample(-1) end diff --git a/test/test_avatar.rb b/test/test_avatar.rb index aa1bb0c32a..5e43043362 100644 --- a/test/test_avatar.rb +++ b/test/test_avatar.rb @@ -6,15 +6,15 @@ def setup end def test_avatar - assert @tester.image.match(/https:\/\/robohash\.org\/(.+)\.png/)[1] != nil + assert !@tester.image.match(%r{https:\/\/robohash\.org\/(.+)\.png})[1].nil? end def test_avatar_with_param - assert @tester.image('faker').match(/https:\/\/robohash\.org\/(.+)\.png/)[1] == 'faker' + assert @tester.image('faker').match(%r{https:\/\/robohash\.org\/(.+)\.png})[1] == 'faker' end def test_avatar_with_correct_size - assert @tester.image('faker', '150x320').match(/https:\/\/robohash\.org\/faker\.png\?size=(.+)&.*/)[1] == '150x320' + assert @tester.image('faker', '150x320').match(%r{https:\/\/robohash\.org\/faker\.png\?size=(.+)&.*})[1] == '150x320' end def test_avatar_with_incorrect_size @@ -24,7 +24,7 @@ def test_avatar_with_incorrect_size end def test_avatar_with_supported_format - assert @tester.image('faker', '300x300', 'jpg').match(/https:\/\/robohash\.org\/faker\.jpg/) + assert @tester.image('faker', '300x300', 'jpg').match(%r{https:\/\/robohash\.org\/faker\.jpg}) end def test_avatar_with_incorrect_format @@ -34,10 +34,10 @@ def test_avatar_with_incorrect_format end def test_avatar_with_set - assert @tester.image('faker', '300x300', 'jpg', 'set2').match(/https:\/\/robohash\.org\/faker\.jpg.*set=set2/) + assert @tester.image('faker', '300x300', 'jpg', 'set2').match(%r{https:\/\/robohash\.org\/faker\.jpg.*set=set2}) end def test_avatar_with_bgset - assert @tester.image('faker', '300x300', 'jpg', 'set1', 'bg1').match(/https:\/\/robohash\.org\/faker\.jpg.*bgset=bg1/) + assert @tester.image('faker', '300x300', 'jpg', 'set1', 'bg1').match(%r{https:\/\/robohash\.org\/faker\.jpg.*bgset=bg1}) end end diff --git a/test/test_ca_cat_locale.rb b/test/test_ca_cat_locale.rb index 1c26f088df..1265a10f5f 100644 --- a/test/test_ca_cat_locale.rb +++ b/test/test_ca_cat_locale.rb @@ -24,12 +24,12 @@ def test_ca_methods end def test_phone_numbers_start_with_9 - mobile = Faker::PhoneNumber.phone_number.gsub(/\D/,'') + mobile = Faker::PhoneNumber.phone_number.gsub(/\D/, '') assert_equal '9', mobile[0] end def test_cell_numbers_start_with_6 - mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/,'') + mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/, '') assert_equal '6', mobile[0] end end diff --git a/test/test_country_code.rb b/test/test_country_code.rb index 7cf7e076bc..f378001fef 100644 --- a/test/test_country_code.rb +++ b/test/test_country_code.rb @@ -17,5 +17,4 @@ def test_country_code_expected_length def test_country_code_long_expected_length assert_equal(3, Faker::Address.country_code_long.length) end - end diff --git a/test/test_de_at_locale.rb b/test/test_de_at_locale.rb index f3d8e92d4c..b22a8d09ea 100644 --- a/test/test_de_at_locale.rb +++ b/test/test_de_at_locale.rb @@ -1,5 +1,3 @@ -# encoding: utf-8 - require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestDeAtLocale < Test::Unit::TestCase diff --git a/test/test_de_locale.rb b/test/test_de_locale.rb index 45f9b80b16..a6a168252e 100644 --- a/test/test_de_locale.rb +++ b/test/test_de_locale.rb @@ -35,12 +35,10 @@ def test_de_methods assert Faker::Book.author.is_a? String assert Faker::Book.publisher.is_a? String - - assert Faker::Food.ingredient.is_a? String assert Faker::Food.spice.is_a? String assert Faker::Food.measurement.is_a? String - + assert Faker::Music.instrument.is_a? String assert Faker::Pokemon.name.is_a? String @@ -57,7 +55,7 @@ def test_de_methods end def test_de_cell_phone_countrycode - mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/,'') + mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/, '') assert_equal '4', mobile[0] assert_equal '9', mobile[1] end diff --git a/test/test_determinism.rb b/test/test_determinism.rb index 0d2a7cf88d..f1ae3a66bf 100644 --- a/test/test_determinism.rb +++ b/test/test_determinism.rb @@ -1,11 +1,9 @@ -# frozen_string_literal: true require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') - +# rubocop:disable Security/Eval,Style/EvalWithLocation class TestDeterminism < Test::Unit::TestCase - def setup - @all_methods= all_methods.freeze - @first_run= [] + @all_methods = all_methods.freeze + @first_run = [] end def test_determinism @@ -20,21 +18,19 @@ def test_determinism end end -private + private - def deterministic_random? first, method_name - second= eval(method_name) - (first== second) || raise( + def deterministic_random?(first, method_name) + second = eval(method_name) + (first == second) || raise( "#{method_name} has an entropy leak; use \"Faker::Config.random.rand\" or \"Array#sample(random: Faker::Config.random)\". Method to lookup for: sample, shuffle, rand" ) end - def store_result method_name - begin - @first_run<< eval(method_name) - rescue => exception - raise %Q[#{method_name} raised "#{exception}"] - end + def store_result(method_name) + @first_run << eval(method_name) + rescue StandardError => exception + raise %(#{method_name} raised "#{exception}") end def all_methods @@ -45,7 +41,7 @@ def all_methods def subclasses Faker.constants.delete_if do |subclass| - [:Base, :Char, :Config, :Date, :Internet, :Time, :VERSION].include?(subclass) + %i[Base Char Config Date Internet Time VERSION].include?(subclass) end.sort end @@ -54,4 +50,5 @@ def subclass_methods(subclass) "Faker::#{subclass}.#{method}" end.sort end -end \ No newline at end of file +end +# rubocop:enable Security/Eval,Style/EvalWithLocation diff --git a/test/test_en_au_locale.rb b/test/test_en_au_locale.rb index d878080a65..c363eb44c3 100644 --- a/test/test_en_au_locale.rb +++ b/test/test_en_au_locale.rb @@ -25,7 +25,7 @@ def test_en_au_default_country end def test_aussie_mobiles_start_with_04 - mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/,'') + mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/, '') assert_equal '0', mobile[0] assert_equal '4', mobile[1] end diff --git a/test/test_en_au_ocker_locale.rb b/test/test_en_au_ocker_locale.rb index d6e2c57c98..fbd73724ff 100644 --- a/test/test_en_au_ocker_locale.rb +++ b/test/test_en_au_ocker_locale.rb @@ -18,7 +18,7 @@ def test_au_ocker_methods_with_en_au_ocker_locale end def test_aussie_mobiles_start_with_04 - mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/,'') + mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/, '') assert_equal '0', mobile[0] assert_equal '4', mobile[1] end diff --git a/test/test_en_ca_locale.rb b/test/test_en_ca_locale.rb index 4d4a56d29f..809d8e6df8 100644 --- a/test/test_en_ca_locale.rb +++ b/test/test_en_ca_locale.rb @@ -44,5 +44,4 @@ def test_ca_postcode expected = /[A-VX-Y][0-9][A-CEJ-NPR-TV-Z] ?[0-9][A-CEJ-NPR-TV-Z][0-9]/ assert_match(expected, Faker::Address.postcode) end - end diff --git a/test/test_en_gb_locale.rb b/test/test_en_gb_locale.rb index 634a926c81..ee2555c2fd 100644 --- a/test/test_en_gb_locale.rb +++ b/test/test_en_gb_locale.rb @@ -18,12 +18,12 @@ def test_en_gb_methods end def test_gb_phone_starts_with_zero - phone = Faker::PhoneNumber.phone_number.gsub(/\D/,'') + phone = Faker::PhoneNumber.phone_number.gsub(/\D/, '') assert_equal '0', phone[0] end def test_gb_cell_phone_starts_with_zero - mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/,'') + mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/, '') assert_equal '0', mobile[0] end @@ -33,7 +33,7 @@ def test_gb_postcode_has_outcode_and_incode end def test_gb_postcode_incode_is_valid - #The letters C I K M O V are not used in the second part of the Postcode. + # The letters C I K M O V are not used in the second part of the Postcode. incode = Faker::Address.postcode.split(' ')[1] assert_match(/\d[ABDEFGHJLNPQRSTUWXYZ]{2}/, incode) end @@ -41,8 +41,8 @@ def test_gb_postcode_incode_is_valid def test_gb_postcode_outcode_is_valid outcode = Faker::Address.postcode.split(' ')[0] assert_includes(2..4, outcode.length) - assert_match(/\w{1,2}\d{1,2}\w?/,outcode) - assert_match(/^[A-PR-UWYZ][A-HK-Y0-9]/,outcode) - assert_match(/\w{1,2}\d{1,2}|\w\d[ABCDEFGHJKPSTUW]|\w\w\d[ABEHMNPRVWXY]/,outcode) + assert_match(/\w{1,2}\d{1,2}\w?/, outcode) + assert_match(/^[A-PR-UWYZ][A-HK-Y0-9]/, outcode) + assert_match(/\w{1,2}\d{1,2}|\w\d[ABCDEFGHJKPSTUW]|\w\w\d[ABEHMNPRVWXY]/, outcode) end end diff --git a/test/test_en_ind_locale.rb b/test/test_en_ind_locale.rb index bff56c2921..ba8e421629 100644 --- a/test/test_en_ind_locale.rb +++ b/test/test_en_ind_locale.rb @@ -28,5 +28,4 @@ def test_en_ind_postal_code def test_en_ind_city assert_match(/(\w+\.? ?){2,3}/, Faker::Address.city) end - end diff --git a/test/test_en_locale.rb b/test/test_en_locale.rb index ad07d0d6dd..56133b9889 100644 --- a/test/test_en_locale.rb +++ b/test/test_en_locale.rb @@ -10,8 +10,8 @@ def teardown end def test_us_states_only_include_states - assert_equal I18n.translate("faker.address.state"), ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'] - assert_equal I18n.translate("faker.address.state_abbr"), ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY'] + assert_equal I18n.translate('faker.address.state'), ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'] + assert_equal I18n.translate('faker.address.state_abbr'), %w[AL AK AZ AR CA CO CT DE FL GA HI ID IL IN IA KS KY LA ME MD MA MI MN MS MO MT NE NV NH NJ NM NY NC ND OH OK OR PA RI SC SD TN TX UT VT VA WA WV WI WY] end def test_us_zip_codes @@ -21,12 +21,12 @@ def test_us_zip_codes def test_valid_id_number id_num = Faker::IDNumber.valid - assert Faker::IDNumber::INVALID_SSN.none? { |regex| id_num =~ regex } + assert(Faker::IDNumber::INVALID_SSN.none? { |regex| id_num =~ regex }) end def test_invalid_id_number id_num = Faker::IDNumber.invalid - assert Faker::IDNumber::INVALID_SSN.any? { |regex| id_num =~ regex } + assert(Faker::IDNumber::INVALID_SSN.any? { |regex| id_num =~ regex }) end def test_values_trimmed @@ -34,8 +34,8 @@ def test_values_trimmed check_hash(en_file) end - def check_hash(myHash) - myHash.each { |key, value| check_value(value) unless (key == 'separator') } + def check_hash(hash) + hash.each { |key, value| check_value(value) unless key == 'separator' } end def check_value(value) diff --git a/test/test_en_nz_locale.rb b/test/test_en_nz_locale.rb index 4f7d52280f..8677f76276 100644 --- a/test/test_en_nz_locale.rb +++ b/test/test_en_nz_locale.rb @@ -17,7 +17,7 @@ def test_nz_methods_with_en_nz_locale end def test_nz_cellphones_start_with_02 - cellphone = Faker::PhoneNumber.cell_phone.gsub(/\D/,'') + cellphone = Faker::PhoneNumber.cell_phone.gsub(/\D/, '') assert_equal '0', cellphone[0] assert_equal '2', cellphone[1] end @@ -42,4 +42,4 @@ def test_team_names_with_en_nz_locale def test_university_names_with_en_nz_locale assert Faker::University.name.is_a? String end -end \ No newline at end of file +end diff --git a/test/test_en_ug_locale.rb b/test/test_en_ug_locale.rb index 892fd68a98..d0acaa770b 100644 --- a/test/test_en_ug_locale.rb +++ b/test/test_en_ug_locale.rb @@ -12,12 +12,11 @@ def teardown def test_validity_of_phone_number validation_regex = /^((0)|(256)|(\+256))((39)|(41))\d{7}$/ - assert_match(validation_regex, Faker::PhoneNumber.phone_number.gsub(' ','')) + assert_match(validation_regex, Faker::PhoneNumber.phone_number.delete(' ')) end def test_validity_of_cell_phone validation_regex = /^((0)|(256)|(\+256))((70)|(71)|(72)|(74)|(75)|(77)|(78)|(79))\d{7}$/ - assert_match(validation_regex, Faker::PhoneNumber.cell_phone.gsub(' ','')) + assert_match(validation_regex, Faker::PhoneNumber.cell_phone.delete(' ')) end - -end \ No newline at end of file +end diff --git a/test/test_en_us_locale.rb b/test/test_en_us_locale.rb index 1f5788e188..063d60e54f 100644 --- a/test/test_en_us_locale.rb +++ b/test/test_en_us_locale.rb @@ -40,7 +40,7 @@ def test_validity_of_phone_method_output end def test_us_invalid_state_raises_exception - assert_raise I18n::MissingTranslationData do Faker::Address.zip_code('NA') end + assert_raise(I18n::MissingTranslationData) { Faker::Address.zip_code('NA') } end def test_us_zip_codes_match_state @@ -72,11 +72,11 @@ def test_us_zip_codes_match_state def test_valid_id_number id_num = Faker::IDNumber.valid - assert Faker::IDNumber::INVALID_SSN.none? { |regex| id_num =~ regex } + assert(Faker::IDNumber::INVALID_SSN.none? { |regex| id_num =~ regex }) end def test_invalid_id_number id_num = Faker::IDNumber.invalid - assert Faker::IDNumber::INVALID_SSN.any? { |regex| id_num =~ regex } + assert(Faker::IDNumber::INVALID_SSN.any? { |regex| id_num =~ regex }) end end diff --git a/test/test_es_locale.rb b/test/test_es_locale.rb index bd7ac0f386..c4b59e3048 100644 --- a/test/test_es_locale.rb +++ b/test/test_es_locale.rb @@ -1,8 +1,7 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') -LoadedEsYaml = ['en', 'es'].inject({}) do |h, locale| +LoadedEsYaml = %w[en es].each_with_object({}) do |locale, h| h[locale] = YAML.load_file(File.expand_path(File.dirname(__FILE__) + "/../lib/locales/#{locale}.yml"))[locale]['faker'] - h end class TestEsLocale < Test::Unit::TestCase @@ -24,7 +23,7 @@ def test_configured_locale_translation end def test_locale_override_when_calling_translate - assert_equal Faker::Base.translate('faker.separator', :locale => :en), LoadedEsYaml['en']['separator'] + assert_equal Faker::Base.translate('faker.separator', locale: :en), LoadedEsYaml['en']['separator'] end def test_translation_fallback diff --git a/test/test_es_mx_locale.rb b/test/test_es_mx_locale.rb index 9b322f491c..ba8cfcfc0e 100644 --- a/test/test_es_mx_locale.rb +++ b/test/test_es_mx_locale.rb @@ -43,5 +43,4 @@ def test_es_mx_methods assert Faker::Name.prefix.is_a? String assert Faker::Name.name.is_a? String end - end diff --git a/test/test_fa_locale.rb b/test/test_fa_locale.rb index 4046c12ca4..4990be9789 100644 --- a/test/test_fa_locale.rb +++ b/test/test_fa_locale.rb @@ -14,5 +14,4 @@ def test_fa_methods assert Faker::Name.last_name.is_a? String assert Faker::Name.prefix.is_a? String end - end diff --git a/test/test_faker.rb b/test/test_faker.rb index 5e81e31990..5e83e718c9 100644 --- a/test/test_faker.rb +++ b/test/test_faker.rb @@ -1,9 +1,7 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFaker < Test::Unit::TestCase - - def setup - end + def setup; end def test_numerify 100.times do @@ -91,7 +89,7 @@ def test_rand_for_range end def test_unique - unique_numbers = 8.times.map do + unique_numbers = Array.new(8) do Faker::Base.unique.numerify('#') end diff --git a/test/test_faker_address.rb b/test/test_faker_address.rb index 6823f233ca..9dd96205a7 100644 --- a/test/test_faker_address.rb +++ b/test/test_faker_address.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerAddress < Test::Unit::TestCase - def setup @tester = Faker::Address end @@ -31,7 +30,7 @@ def test_zip_code end def test_time_zone - assert @tester.time_zone.match(/\w+\/\w+/) + assert @tester.time_zone.match(%r{\w+\/\w+}) end def test_street_suffix diff --git a/test/test_faker_ancient.rb b/test/test_faker_ancient.rb index 84795e4ef0..b6dee236b6 100644 --- a/test/test_faker_ancient.rb +++ b/test/test_faker_ancient.rb @@ -20,5 +20,4 @@ def test_titan def test_hero assert @tester.hero.match(/\w+/) end - end diff --git a/test/test_faker_app.rb b/test/test_faker_app.rb index f1d9d4c979..1142eb21a9 100644 --- a/test/test_faker_app.rb +++ b/test/test_faker_app.rb @@ -10,8 +10,8 @@ def test_name end def test_basic_semantic_version - 10.times do |digits| - test_sem_vers = @tester.semantic_version().split(".") + 10.times do |_digits| + test_sem_vers = @tester.semantic_version.split('.') assert test_sem_vers[0].match(/[0-9]{1}/) assert test_sem_vers[1].match(/[0-9]{1}/) assert test_sem_vers[2].match(/[1-9]{1}/) @@ -19,8 +19,8 @@ def test_basic_semantic_version end def test_major_semantic_version - 10.times do |digits| - test_sem_vers = @tester.semantic_version(major: (1000..9999)).split(".") + 10.times do |_digits| + test_sem_vers = @tester.semantic_version(major: (1000..9999)).split('.') assert test_sem_vers[0].match(/[0-9]{4}/) assert test_sem_vers[1].match(/[0-9]{1}/) assert test_sem_vers[2].match(/[1-9]{1}/) @@ -28,8 +28,8 @@ def test_major_semantic_version end def test_minor_semantic_version - 10.times do |digits| - test_sem_vers = @tester.semantic_version(minor: (1000..9999)).split(".") + 10.times do |_digits| + test_sem_vers = @tester.semantic_version(minor: (1000..9999)).split('.') assert test_sem_vers[0].match(/[0-9]{1}/) assert test_sem_vers[1].match(/[0-9]{4}/) assert test_sem_vers[2].match(/[1-9]{1}/) @@ -37,8 +37,8 @@ def test_minor_semantic_version end def test_patch_semantic_version - 10.times do |digits| - test_sem_vers = @tester.semantic_version(patch: (1000..9999)).split(".") + 10.times do |_digits| + test_sem_vers = @tester.semantic_version(patch: (1000..9999)).split('.') assert test_sem_vers[0].match(/[0-9]{1}/) assert test_sem_vers[1].match(/[0-9]{1}/) assert test_sem_vers[2].match(/[0-9]{4}/) @@ -46,8 +46,8 @@ def test_patch_semantic_version end def test_all_semantic_version - 10.times do |digits| - test_sem_vers = @tester.semantic_version(major: (1000..9999), minor: (1000..9999), patch: (1000..9999)).split(".") + 10.times do |_digits| + test_sem_vers = @tester.semantic_version(major: (1000..9999), minor: (1000..9999), patch: (1000..9999)).split('.') assert test_sem_vers[0].match(/[0-9]{4}/) assert test_sem_vers[1].match(/[0-9]{4}/) assert test_sem_vers[2].match(/[0-9]{4}/) @@ -57,5 +57,4 @@ def test_all_semantic_version def test_specific_major_version assert @tester.semantic_version(major: 42).match(/42\.[0-9]\.[0-9]/) end - end diff --git a/test/test_faker_aqua_teen_hunger_force.rb b/test/test_faker_aqua_teen_hunger_force.rb index 0649472ccf..276fae5043 100644 --- a/test/test_faker_aqua_teen_hunger_force.rb +++ b/test/test_faker_aqua_teen_hunger_force.rb @@ -1,13 +1,11 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') - class TestFakerAquaTeenHungerForce < Test::Unit::TestCase - - def setup - @tester = Faker::AquaTeenHungerForce - end - - def test_character - assert @tester.character.match(/\w/) - end - - end +class TestFakerAquaTeenHungerForce < Test::Unit::TestCase + def setup + @tester = Faker::AquaTeenHungerForce + end + + def test_character + assert @tester.character.match(/\w/) + end +end diff --git a/test/test_faker_bank.rb b/test/test_faker_bank.rb index ce07fb262c..d7fc3898a4 100644 --- a/test/test_faker_bank.rb +++ b/test/test_faker_bank.rb @@ -1,8 +1,7 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerBank < Test::Unit::TestCase - - IBAN_HEADER = '[A-Z]{2}[0-9]{2}' + IBAN_HEADER = '[A-Z]{2}[0-9]{2}'.freeze def setup @tester = Faker::Bank @@ -498,8 +497,8 @@ def test_iban_xk end def test_iban_invalid - assert_raise ArgumentError.new("Could not find iban details for bad") do - @tester.iban("bad") + assert_raise ArgumentError.new('Could not find iban details for bad') do + @tester.iban('bad') end end end diff --git a/test/test_faker_beer.rb b/test/test_faker_beer.rb index ab5f827dc7..854a684c55 100644 --- a/test/test_faker_beer.rb +++ b/test/test_faker_beer.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerBeer < Test::Unit::TestCase - def setup @tester = Faker::Beer end @@ -37,5 +36,4 @@ def test_alcohol def test_blg assert @tester.blg.match(/(\w+\.? ?){2,3}/) end - -end \ No newline at end of file +end diff --git a/test/test_faker_birthday_in_leap_year.rb b/test/test_faker_birthday_in_leap_year.rb index 4dc91aaaf8..5e5e35c437 100644 --- a/test/test_faker_birthday_in_leap_year.rb +++ b/test/test_faker_birthday_in_leap_year.rb @@ -3,7 +3,7 @@ class TestFakerBirthdayInLeapYear < Test::Unit::TestCase def setup @tester = Faker::Date - @today = Date.parse("2016-02-29") + @today = Date.parse('2016-02-29') @min = 18 @max = 65 end @@ -19,11 +19,11 @@ def test_birthday_in_leap_year end assert_raise ArgumentError do - ::Date.new(@today.year - @min, @today.month, @today.day) + ::Date.new(@today.year - @min, @today.month, @today.day) end assert_raise ArgumentError do - ::Date.new(@today.year - @max, @today.month, @today.day) + ::Date.new(@today.year - @max, @today.month, @today.day) end end end diff --git a/test/test_faker_bitcoin.rb b/test/test_faker_bitcoin.rb index 4993c9f954..cd3a00ef17 100644 --- a/test/test_faker_bitcoin.rb +++ b/test/test_faker_bitcoin.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerBitcoin < Test::Unit::TestCase - def test_address assert Faker::Bitcoin.address.match(/^[13][1-9A-Za-z][^OIl]{20,40}/) end @@ -17,5 +16,4 @@ def test_testnet_address assert_match(/\A[mn][1-9A-Za-z]{32,34}\Z/, Faker::Bitcoin.testnet_address) assert_not_match(/[OIl]/, Faker::Bitcoin.testnet_address) end - end diff --git a/test/test_faker_book.rb b/test/test_faker_book.rb index eb5ad8c5cb..b3c7619a3f 100644 --- a/test/test_faker_book.rb +++ b/test/test_faker_book.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerBook < Test::Unit::TestCase - def setup @tester = Faker::Book end diff --git a/test/test_faker_breaking_bad.rb b/test/test_faker_breaking_bad.rb index c513d22079..cfd8087f98 100644 --- a/test/test_faker_breaking_bad.rb +++ b/test/test_faker_breaking_bad.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 # frozen_string_literal: true require File.expand_path(File.dirname(__FILE__) + '/test_helper') diff --git a/test/test_faker_business.rb b/test/test_faker_business.rb index 90aaea2fb0..7b587ba2ef 100644 --- a/test/test_faker_business.rb +++ b/test/test_faker_business.rb @@ -1,7 +1,6 @@ require File.dirname(__FILE__) + '/test_helper.rb' class TestFakerBusiness < Test::Unit::TestCase - def setup @tester = Faker::Business @credit_card_number_list = I18n.translate('faker.business.credit_card_numbers') @@ -30,5 +29,4 @@ def test_credit_card_type assert @credit_card_types.include?(type1) assert @credit_card_types.include?(type2) end - end diff --git a/test/test_faker_cat.rb b/test/test_faker_cat.rb index abc61dcab2..a1053d0e9e 100644 --- a/test/test_faker_cat.rb +++ b/test/test_faker_cat.rb @@ -16,5 +16,4 @@ def test_breed def test_registry assert @tester.registry.match(/\w+\.?/) end - end diff --git a/test/test_faker_chuck_norris.rb b/test/test_faker_chuck_norris.rb index 3953916cc6..cc090f6494 100644 --- a/test/test_faker_chuck_norris.rb +++ b/test/test_faker_chuck_norris.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerChuckNorris < Test::Unit::TestCase - def setup @tester = Faker::ChuckNorris end diff --git a/test/test_faker_city.rb b/test/test_faker_city.rb index a27a2ff19a..4dc6411999 100644 --- a/test/test_faker_city.rb +++ b/test/test_faker_city.rb @@ -4,27 +4,29 @@ class TestFakerCity < Test::Unit::TestCase def setup @old_locales = I18n.config.available_locales xx = { - :faker => { - :name => {:first_name => ['alice'], :last_name => ['smith']}, - :address => {:city_prefix => ['west'], :city_suffix => ['burg']} + faker: { + name: { first_name: ['alice'], last_name: ['smith'] }, + address: { city_prefix: ['west'], city_suffix: ['burg'] } } } I18n.backend.store_translations(:xx, xx) - I18n.config.available_locales += [ :xx ] + I18n.config.available_locales += [:xx] + # rubocop:disable Lint/InterpolationCheck xy = { - :faker => { - :address => { - :city_prefix => ['big'], - :city_root => ['rock'], - :city_root_suffix => ['ing'], - :city_suffix => ['town'], - :city => ['#{city_prefix} #{city_root}#{city_root_suffix} #{city_suffix}'] + faker: { + address: { + city_prefix: ['big'], + city_root: ['rock'], + city_root_suffix: ['ing'], + city_suffix: ['town'], + city: ['#{city_prefix} #{city_root}#{city_root_suffix} #{city_suffix}'] } } } + # rubocop:enable Lint/InterpolationCheck I18n.backend.store_translations(:xy, xy) - I18n.config.available_locales += [ :xy ] + I18n.config.available_locales += [:xy] end def teardown @@ -34,7 +36,7 @@ def teardown def test_default_city_formats I18n.with_locale(:xx) do 100.times do - cities = ["west alice", "west smith", "west aliceburg", "west smithburg", "aliceburg", "smithburg"] + cities = ['west alice', 'west smith', 'west aliceburg', 'west smithburg', 'aliceburg', 'smithburg'] city = Faker::Address.city assert cities.include?(city), "Expected <#{cities.join(' / ')}>, but got #{city}" end @@ -48,5 +50,4 @@ def test_city_formats_are_flexible assert cities.include?(city), "Expected <#{cities.join(' / ')}>, but got #{city}" end end - end diff --git a/test/test_faker_coffee.rb b/test/test_faker_coffee.rb index c983a6b3d8..a4976e3f17 100644 --- a/test/test_faker_coffee.rb +++ b/test/test_faker_coffee.rb @@ -16,7 +16,8 @@ def setup def test_origin assert origin = @tester.origin.match(/\A(?([[:alnum:]]+'?-?.?,?\s?){1,5}), (?([[:alnum:]]+\s?){1,5})\z/) - region, country = origin[:region], origin[:country] + region = origin[:region] + country = origin[:country] search_format_country = country.split.length > 1 ? country.downcase.split.join('_') : country.downcase regions = Faker::Base.fetch_all("coffee.regions.#{search_format_country}") @@ -26,7 +27,7 @@ def test_origin def test_notes assert notes = @tester.notes - .match(/\A(?[\s\w-]+), (?[\s\w-]+), (?[!\s\w-]+), (?[!\s\w-]+), (?[!\s\w-]+)\z/) + .match(/\A(?[\s\w-]+), (?[\s\w-]+), (?[!\s\w-]+), (?[!\s\w-]+), (?[!\s\w-]+)\z/) assert @intensifiers.include?(notes[:intensifier]) assert @body_descriptors.include?(notes[:body]) diff --git a/test/test_faker_color.rb b/test/test_faker_color.rb index c9fd46281b..3ab1370479 100644 --- a/test/test_faker_color.rb +++ b/test/test_faker_color.rb @@ -37,7 +37,7 @@ def test_hsl_color else assert @result[0].is_a?(Integer) end - + assert @result[1].between?(0.0, 1.0) assert @result[2].between?(0.0, 1.0) end diff --git a/test/test_faker_commerce.rb b/test/test_faker_commerce.rb index a33e81f16d..df6682e78e 100644 --- a/test/test_faker_commerce.rb +++ b/test/test_faker_commerce.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerCommerce < Test::Unit::TestCase - def setup @tester = Faker::Commerce end @@ -33,16 +32,16 @@ def test_department_should_have_ampersand_as_default_separator def test_department_should_accept_localized_separator @old_locales = I18n.config.available_locales data = { - :faker => { - :separator => ' + ', - :commerce => { - :department => ['Books', 'Movies'] + faker: { + separator: ' + ', + commerce: { + department: %w[Books Movies] } } } I18n.backend.store_translations(:xy, data) - I18n.config.available_locales += [ :xy ] + I18n.config.available_locales += [:xy] I18n.with_locale(:xy) do assert_match ' + ', @tester.department(2, true) end @@ -82,7 +81,7 @@ def test_price end def test_price_with_srand - Faker::Config.random = Random.new(12345) + Faker::Config.random = Random.new(12_345) assert_equal 92.96, @tester.price end diff --git a/test/test_faker_company.rb b/test/test_faker_company.rb index 97d1c316ed..d576667a24 100644 --- a/test/test_faker_company.rb +++ b/test/test_faker_company.rb @@ -24,7 +24,7 @@ def test_buzzword def test_spanish_organisation_number org_no = @tester.spanish_organisation_number assert org_no.match(/\D\d{7}/) - assert ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'N', 'P', 'Q', 'R', 'S', 'U', 'V', 'W'].include?(org_no[0].to_s) + assert %w[A B C D E F G H J N P Q R S U V W].include?(org_no[0].to_s) end def test_swedish_organisation_number @@ -60,7 +60,7 @@ def test_australian_business_number checksum = abn_checksum(abn) assert abn.match(/\d{11}/) - assert checksum % 89 == 0 + assert((checksum % 89).zero?) end def test_profession @@ -69,12 +69,11 @@ def test_profession private - def abn_checksum(abn) - abn_weights = [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19] - - abn.split('').map(&:to_i).each_with_index.map do |n, i| - (i == 0 ? n-1 : n) * abn_weights[i] - end.inject(:+) - end + def abn_checksum(abn) + abn_weights = [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19] + abn.split('').map(&:to_i).each_with_index.map do |n, i| + (i.zero? ? n - 1 : n) * abn_weights[i] + end.inject(:+) + end end diff --git a/test/test_faker_date.rb b/test/test_faker_date.rb index 7c9b6f4297..2545b1e514 100644 --- a/test/test_faker_date.rb +++ b/test/test_faker_date.rb @@ -6,20 +6,20 @@ def setup end def test_between - from = Date.parse("2012-01-01") - to = Date.parse("2013-01-01") + from = Date.parse('2012-01-01') + to = Date.parse('2013-01-01') 100.times do random_date = @tester.between(from, to) assert random_date >= from, "Expected >= \"#{from}\", but got #{random_date}" - assert random_date <= to , "Expected <= \"#{to}\", but got #{random_date}" + assert random_date <= to, "Expected <= \"#{to}\", but got #{random_date}" end end def test_between_except - from = Date.parse("2012-01-01") - to = Date.parse("2012-01-05") - excepted = Date.parse("2012-01-03") + from = Date.parse('2012-01-01') + to = Date.parse('2012-01-05') + excepted = Date.parse('2012-01-03') 100.times do random_date = @tester.between_except(from, to, excepted) @@ -29,9 +29,9 @@ def test_between_except end def test_between_except_with_strings - from = "2012-01-01" - to = "2012-01-05" - excepted = "2012-01-03" + from = '2012-01-01' + to = '2012-01-05' + excepted = '2012-01-03' excepted_date = Date.parse(excepted) @@ -44,7 +44,7 @@ def test_between_except_with_strings def test_between_except_with_same_from_to_and_except assert_raise ArgumentError do - @tester.between_except("2012-01-01", "2012-01-01", "2012-01-01") + @tester.between_except('2012-01-01', '2012-01-01', '2012-01-01') end end @@ -78,7 +78,7 @@ def test_return_type def test_invalid_date assert_raise ArgumentError do - @tester.between("9999-99-99", "9999-99-99") + @tester.between('9999-99-99', '9999-99-99') end end diff --git a/test/test_faker_demographic.rb b/test/test_faker_demographic.rb index db2a6d4d06..5861eecf2b 100644 --- a/test/test_faker_demographic.rb +++ b/test/test_faker_demographic.rb @@ -22,7 +22,7 @@ def test_demonym end def test_sex - assert ["Male", "Female"].include?(@tester.sex) + assert %w[Male Female].include?(@tester.sex) end def test_height diff --git a/test/test_faker_dessert.rb b/test/test_faker_dessert.rb index 6e0017b429..8fe6e2cbfe 100644 --- a/test/test_faker_dessert.rb +++ b/test/test_faker_dessert.rb @@ -16,5 +16,4 @@ def test_topping def test_flavor assert @tester.flavor.match(/\w+\.?/) end - end diff --git a/test/test_faker_dr_who.rb b/test/test_faker_dr_who.rb index 0dc2f74178..6875fd0d3a 100644 --- a/test/test_faker_dr_who.rb +++ b/test/test_faker_dr_who.rb @@ -1,15 +1,12 @@ -#encoding: utf-8 -#frozen_string_literal: true +# frozen_string_literal: true require File.expand_path(File.dirname(__FILE__) + '/test_helper') class TestFakerDrWho < Test::Unit::TestCase - def setup Faker::Config.locale = nil end - def test_character 10.times { assert Faker::DrWho.character.match(/[\w]+/) } end @@ -34,10 +31,8 @@ def test_specie 10.times { assert Faker::DrWho.specie.match(/[\w]+/) } end - def test_locales - [nil,'en','de',#... - ].each do |locale_name| + [nil, 'en', 'de'].each do |_locale_name| Faker::Config.locale = 'de' assert Faker::DrWho.character .is_a? String assert Faker::DrWho.the_doctor .is_a? String @@ -47,5 +42,4 @@ def test_locales assert Faker::DrWho.specie .is_a? String end end - -end #class TestFakerDrWho +end diff --git a/test/test_faker_dumb_and_dumber.rb b/test/test_faker_dumb_and_dumber.rb index 2e3b366796..23f3796866 100644 --- a/test/test_faker_dumb_and_dumber.rb +++ b/test/test_faker_dumb_and_dumber.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerDumbAndDumber < Test::Unit::TestCase - def setup @tester = Faker::DumbAndDumber end diff --git a/test/test_faker_dune.rb b/test/test_faker_dune.rb index 9837fdcade..c60dbfdb13 100644 --- a/test/test_faker_dune.rb +++ b/test/test_faker_dune.rb @@ -23,13 +23,13 @@ def test_random_quote # test good match def test_random_character_quote - assert @tester.quote("paul").match(/\w+/) + assert @tester.quote('paul').match(/\w+/) end # test error on no match def test_invalid_quote assert_raise ArgumentError do - @tester.quote("Luke Skywalker") + @tester.quote('Luke Skywalker') end end @@ -39,14 +39,13 @@ def test_random_saying # test good match def test_random_source_saying - assert @tester.saying("fremen").match(/\w+/) + assert @tester.saying('fremen').match(/\w+/) end # test error on no match def test_invalid_saying assert_raise ArgumentError do - @tester.saying("Ewoks") + @tester.saying('Ewoks') end end - end diff --git a/test/test_faker_educator.rb b/test/test_faker_educator.rb index 418890e7f2..9c237376e9 100644 --- a/test/test_faker_educator.rb +++ b/test/test_faker_educator.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerEducator < Test::Unit::TestCase - def setup @tester = Faker::Educator end @@ -21,5 +20,4 @@ def test_secondary_school def test_campus assert @tester.campus.match(/(\w+\.? ?){1,2}/) end - end diff --git a/test/test_faker_elder_scrolls.rb b/test/test_faker_elder_scrolls.rb index 9a0c5e5520..5dd69e23ba 100644 --- a/test/test_faker_elder_scrolls.rb +++ b/test/test_faker_elder_scrolls.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerElderScrolls < Test::Unit::TestCase - def setup @tester = Faker::ElderScrolls end diff --git a/test/test_faker_family_guy.rb b/test/test_faker_family_guy.rb index 5e4527d2a9..491f63f1d2 100644 --- a/test/test_faker_family_guy.rb +++ b/test/test_faker_family_guy.rb @@ -1,21 +1,19 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') - class TestFakerFamilyGuy < Test::Unit::TestCase +class TestFakerFamilyGuy < Test::Unit::TestCase + def setup + @tester = Faker::FamilyGuy + end - def setup - @tester = Faker::FamilyGuy - end + def test_character + assert @tester.character.match(/\w/) + end - def test_character - assert @tester.character.match(/\w/) - end + def test_location + assert @tester.location.match(/\w/) + end - def test_location - assert @tester.location.match(/\w/) - end - - def test_quote - assert @tester.quote.match(/\w/) - end - - end + def test_quote + assert @tester.quote.match(/\w/) + end +end diff --git a/test/test_faker_file.rb b/test/test_faker_file.rb index b892c3c8b6..da8a0e9330 100644 --- a/test/test_faker_file.rb +++ b/test/test_faker_file.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerFile < Test::Unit::TestCase - def setup @tester = Faker::File end @@ -11,11 +10,10 @@ def test_extension end def test_mime_type_format - assert @tester.mime_type.match(/(.*)\/(.*)+/) + assert @tester.mime_type.match(%r{(.*)\/(.*)+}) end def test_file_name - assert @tester.file_name.match(/([a-z\-_]+)(\\|\/)([a-z\-_]+)\.([a-z]+)/) + assert @tester.file_name.match(%r{([a-z\-_]+)(\\|\/)([a-z\-_]+)\.([a-z]+)}) end - end diff --git a/test/test_faker_fillmurray.rb b/test/test_faker_fillmurray.rb index 3450a1562e..a6210a95f4 100644 --- a/test/test_faker_fillmurray.rb +++ b/test/test_faker_fillmurray.rb @@ -6,18 +6,17 @@ def setup end def test_fillmurray - assert @tester.image(false, '300', '300').match(/https:\/\/fillmurray\.com\/(\d+)\/(\d+)/) != nil + assert !@tester.image(false, '300', '300').match(%r{https:\/\/fillmurray\.com\/(\d+)\/(\d+)}).nil? end def test_fillmurray_with_grayscale - assert @tester.image(true, '300', '300').match(/https:\/\/fillmurray\.com\/(g?\/?)(\d+)\/(\d+)/)[1] == 'g/' + assert @tester.image(true, '300', '300').match(%r{https:\/\/fillmurray\.com\/(g?\/?)(\d+)\/(\d+)})[1] == 'g/' end def test_fillmurray_with_incorrect_height_format assert_raise ArgumentError do @tester.image(false, '300', 'nine-thousand') end - end def test_fillmurray_with_incorrect_width_format diff --git a/test/test_faker_food.rb b/test/test_faker_food.rb index 8bbeaf2d8d..16c1083fb0 100644 --- a/test/test_faker_food.rb +++ b/test/test_faker_food.rb @@ -22,10 +22,10 @@ def test_spice end def test_measurement - assert @tester.measurement.split(" ").length == 2 + assert @tester.measurement.split(' ').length == 2 end - + def test_metric_measurement assert @tester.metric_measurement.match(/\w+/) - end + end end diff --git a/test/test_faker_funny_name.rb b/test/test_faker_funny_name.rb index 44d2498b0f..51ffb894c7 100644 --- a/test/test_faker_funny_name.rb +++ b/test/test_faker_funny_name.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerFunnyName < Test::Unit::TestCase - def setup @tester = Faker::FunnyName end diff --git a/test/test_faker_hacker_talk.rb b/test/test_faker_hacker_talk.rb index 362a7211c0..603ef210f6 100644 --- a/test/test_faker_hacker_talk.rb +++ b/test/test_faker_hacker_talk.rb @@ -2,14 +2,14 @@ class TestFakerHacker < Test::Unit::TestCase def setup - @hacker = Faker::Hacker - @phrases = @hacker.phrases + @hacker = Faker::Hacker + @phrases = @hacker.phrases end def test_phrases assert @phrases.size == 8 @phrases.each do |phrase| - refute phrase.to_s.empty? + refute phrase.to_s.empty? end end @@ -32,5 +32,4 @@ def test_verb def test_ingverb assert @hacker.ingverb.match(/\w+/) end - end diff --git a/test/test_faker_hipster.rb b/test/test_faker_hipster.rb index a916374448..0c37254b7f 100644 --- a/test/test_faker_hipster.rb +++ b/test/test_faker_hipster.rb @@ -1,7 +1,6 @@ require File.dirname(__FILE__) + '/test_helper.rb' class TestFakerHipster < Test::Unit::TestCase - def setup @tester = Faker::Hipster @standard_wordlist = I18n.translate('faker.hipster.words') @@ -23,7 +22,7 @@ def test_words_without_spaces # Words requested from the supplemental list should all be in that list. def test_supplemental_words - @words = @tester.words(10000, true) + @words = @tester.words(10_000, true) @words.each { |w| assert @complete_wordlist.include?(w) } end @@ -51,15 +50,15 @@ def test_range_count_param ss = @tester.sentences(2..5) ps = @tester.paragraphs(2..5) - assert(2 <= ws.length && ws.length <= 5) - assert(2 <= ss.length && ss.length <= 5) - assert(2 <= ps.length && ps.length <= 5) + assert(ws.length >= 2 && ws.length <= 5) + assert(ss.length >= 2 && ss.length <= 5) + assert(ps.length >= 2 && ps.length <= 5) end def test_array_count_param - ws = @tester.words([1,4]) - ss = @tester.sentences([1,4]) - ps = @tester.paragraphs([1,4]) + ws = @tester.words([1, 4]) + ss = @tester.sentences([1, 4]) + ps = @tester.paragraphs([1, 4]) assert(ws.length == 1 || ws.length == 4) assert(ss.length == 1 || ss.length == 4) @@ -72,7 +71,7 @@ def test_words_with_large_count_params array = @tester.words([250, 500]) assert(exact.length == 500) - assert(250 <= range.length && range.length <= 500) + assert(range.length >= 250 && range.length <= 500) assert(array.length == 250 || array.length == 500) end end diff --git a/test/test_faker_internet.rb b/test/test_faker_internet.rb index 50153396bf..822149053f 100644 --- a/test/test_faker_internet.rb +++ b/test/test_faker_internet.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerInternet < Test::Unit::TestCase - def setup @tester = Faker::Internet end @@ -39,7 +38,7 @@ def test_user_name_with_integer_arg end def test_user_name_with_very_large_integer_arg - exception = assert_raises(ArgumentError) { @tester.user_name(10000000) } + exception = assert_raises(ArgumentError) { @tester.user_name(10_000_000) } assert_equal('Given argument is too large', exception.message) end @@ -55,19 +54,19 @@ def test_user_name_with_closed_range_arg def test_user_name_with_open_range_arg (1..32).each do |min_length| - (min_length+1..33).each do |max_length| + (min_length + 1..33).each do |max_length| l = @tester.user_name((min_length...max_length)).length assert l >= min_length - assert l <= max_length-1 + assert l <= max_length - 1 end end end def test_user_name_with_range_and_separators (1..32).each do |min_length| - (min_length+1..33).each do |max_length| - u = @tester.user_name((min_length...max_length), %w(=)) - assert u.length.between? min_length, max_length-1 + (min_length + 1..33).each do |max_length| + u = @tester.user_name((min_length...max_length), %w[=]) + assert u.length.between? min_length, max_length - 1 assert u.match(/\A[a-z]+((=)?[a-z]*)*\z/) end end @@ -122,22 +121,22 @@ def test_ip_v4_address assert_equal 3, @tester.ip_v4_address.count('.') 100.times do - assert @tester.ip_v4_address.split('.').map{|octet| octet.to_i}.max <= 255 + assert @tester.ip_v4_address.split('.').map(&:to_i).max <= 255 end end def test_private_ip_v4_address regexps = [ - /^10\./, # 10.0.0.0 – 10.255.255.255 - /^100\.(6[4-9]|[7-9]\d|1[0-1]\d|12[0-7])\./, # 100.64.0.0 – 100.127.255.255 - /^127\./, # 127.0.0.0 – 127.255.255.255 - /^169\.254\./, # 169.254.0.0 – 169.254.255.255 - /^172\.(1[6-9]|2\d|3[0-1])\./, # 172.16.0.0 – 172.31.255.255 - /^192\.0\.0\./, # 192.0.0.0 – 192.0.0.255 - /^192\.168\./, # 192.168.0.0 – 192.168.255.255 - /^198\.(1[8-9])\./ # 198.18.0.0 – 198.19.255.255 + /^10\./, # 10.0.0.0 - 10.255.255.255 + /^100\.(6[4-9]|[7-9]\d|1[0-1]\d|12[0-7])\./, # 100.64.0.0 - 100.127.255.255 + /^127\./, # 127.0.0.0 - 127.255.255.255 + /^169\.254\./, # 169.254.0.0 - 169.254.255.255 + /^172\.(1[6-9]|2\d|3[0-1])\./, # 172.16.0.0 - 172.31.255.255 + /^192\.0\.0\./, # 192.0.0.0 - 192.0.0.255 + /^192\.168\./, # 192.168.0.0 - 192.168.255.255 + /^198\.(1[8-9])\./ # 198.18.0.0 - 198.19.255.255 ] - expected = Regexp.new regexps.collect{|reg| "(#{reg})"}.join('|') + expected = Regexp.new regexps.collect { |reg| "(#{reg})" }.join('|') 1000.times do address = @tester.private_ip_v4_address @@ -147,24 +146,24 @@ def test_private_ip_v4_address def test_public_ip_v4_address private = [ - /^10\./, # 10.0.0.0 – 10.255.255.255 - /^100\.(6[4-9]|[7-9]\d|1[0-1]\d|12[0-7])\./, # 100.64.0.0 – 100.127.255.255 - /^127\./, # 127.0.0.0 – 127.255.255.255 - /^169\.254\./, # 169.254.0.0 – 169.254.255.255 - /^172\.(1[6-9]|2\d|3[0-1])\./, # 172.16.0.0 – 172.31.255.255 - /^192\.0\.0\./, # 192.0.0.0 – 192.0.0.255 - /^192\.168\./, # 192.168.0.0 – 192.168.255.255 - /^198\.(1[8-9])\./ # 198.18.0.0 – 198.19.255.255 + /^10\./, # 10.0.0.0 - 10.255.255.255 + /^100\.(6[4-9]|[7-9]\d|1[0-1]\d|12[0-7])\./, # 100.64.0.0 - 100.127.255.255 + /^127\./, # 127.0.0.0 - 127.255.255.255 + /^169\.254\./, # 169.254.0.0 - 169.254.255.255 + /^172\.(1[6-9]|2\d|3[0-1])\./, # 172.16.0.0 - 172.31.255.255 + /^192\.0\.0\./, # 192.0.0.0 - 192.0.0.255 + /^192\.168\./, # 192.168.0.0 - 192.168.255.255 + /^198\.(1[8-9])\./ # 198.18.0.0 - 198.19.255.255 ] reserved = [ - /^0\./, # 0.0.0.0 – 0.255.255.255 - /^192\.0\.2\./, # 192.0.2.0 – 192.0.2.255 - /^192\.88\.99\./, # 192.88.99.0 – 192.88.99.255 - /^198\.51\.100\./, # 198.51.100.0 – 198.51.100.255 - /^203\.0\.113\./, # 203.0.113.0 – 203.0.113.255 - /^(22[4-9]|23\d)\./, # 224.0.0.0 – 239.255.255.255 - /^(24\d|25[0-5])\./ # 240.0.0.0 – 255.255.255.254 and 255.255.255.255 + /^0\./, # 0.0.0.0 - 0.255.255.255 + /^192\.0\.2\./, # 192.0.2.0 - 192.0.2.255 + /^192\.88\.99\./, # 192.88.99.0 - 192.88.99.255 + /^198\.51\.100\./, # 198.51.100.0 - 198.51.100.255 + /^203\.0\.113\./, # 203.0.113.0 - 203.0.113.255 + /^(22[4-9]|23\d)\./, # 224.0.0.0 - 239.255.255.255 + /^(24\d|25[0-5])\./ # 240.0.0.0 - 255.255.255.254 and 255.255.255.255 ] 1000.times do @@ -175,38 +174,38 @@ def test_public_ip_v4_address end def test_ip_v4_cidr - assert @tester.ip_v4_cidr.match(/\/\d{1,2}$/) + assert @tester.ip_v4_cidr.match(%r(\/\d{1,2}$)) 1000.times do - assert (1..32).include?(@tester.ip_v4_cidr.split('/').last.to_i) + assert((1..32).cover?(@tester.ip_v4_cidr.split('/').last.to_i)) end end def test_mac_address assert_equal 5, @tester.mac_address.count(':') - assert_equal 5, @tester.mac_address("").count(':') + assert_equal 5, @tester.mac_address('').count(':') 100.times do - assert @tester.mac_address.split(':').map{|d| d.to_i(16)}.max <= 255 + assert @tester.mac_address.split(':').map { |d| d.to_i(16) }.max <= 255 end - assert @tester.mac_address("fa:fa:fa").start_with?("fa:fa:fa") - assert @tester.mac_address("01:02").start_with?("01:02") + assert @tester.mac_address('fa:fa:fa').start_with?('fa:fa:fa') + assert @tester.mac_address('01:02').start_with?('01:02') end def test_ip_v6_address assert_equal 7, @tester.ip_v6_address.count(':') 100.times do - assert @tester.ip_v6_address.split('.').map{|h| "0x#{h}".hex}.max <= 65535 + assert @tester.ip_v6_address.split('.').map { |h| "0x#{h}".hex }.max <= 65_535 end end def test_ip_v6_cidr - assert @tester.ip_v6_cidr.match(/\/\d{1,3}$/) + assert @tester.ip_v6_cidr.match(%r{\/\d{1,3}$}) 1000.times do - assert (1..128).include?(@tester.ip_v6_cidr.split('/').last.to_i) + assert((1..128).cover?(@tester.ip_v6_cidr.split('/').last.to_i)) end end @@ -223,7 +222,7 @@ def test_slug_with_glue_arg end def test_url - assert @tester.url('domain.com', '/username', 'https').match(/^https:\/\/domain\.com\/username$/) + assert @tester.url('domain.com', '/username', 'https').match(%r{^https:\/\/domain\.com\/username$}) end def test_device_token @@ -236,7 +235,7 @@ def test_user_agent_with_no_argument def test_user_agent_with_valid_argument assert @tester.user_agent(:opera).match(/Opera/) - assert @tester.user_agent("opera").match(/Opera/) + assert @tester.user_agent('opera').match(/Opera/) end def test_user_agent_with_invalid_argument diff --git a/test/test_faker_job.rb b/test/test_faker_job.rb index f00bffd64d..9eb073f2e9 100644 --- a/test/test_faker_job.rb +++ b/test/test_faker_job.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerJob < Test::Unit::TestCase - def setup @tester = Faker::Job end diff --git a/test/test_faker_kpop.rb b/test/test_faker_kpop.rb index cebb7da4b6..135ebe0432 100644 --- a/test/test_faker_kpop.rb +++ b/test/test_faker_kpop.rb @@ -1,6 +1,5 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') - class TestFakerKpop < Test::Unit::TestCase def setup @tester = Faker::Kpop diff --git a/test/test_faker_lebowski.rb b/test/test_faker_lebowski.rb index 8118fa8820..8280f0c7ce 100644 --- a/test/test_faker_lebowski.rb +++ b/test/test_faker_lebowski.rb @@ -1,15 +1,14 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerLebowski < Test::Unit::TestCase - def setup @tester = Faker::Lebowski end - + def test_actor assert @tester.actor.match(/\w+/) end - + def test_character assert @tester.character.match(/\w+/) end @@ -17,4 +16,4 @@ def test_character def test_quote assert @tester.quote.match(/\w+/) end -end \ No newline at end of file +end diff --git a/test/test_faker_lorem.rb b/test/test_faker_lorem.rb index 14907991fa..b87f1d96d4 100644 --- a/test/test_faker_lorem.rb +++ b/test/test_faker_lorem.rb @@ -1,7 +1,6 @@ require File.dirname(__FILE__) + '/test_helper.rb' class TestFakerLorem < Test::Unit::TestCase - def setup @tester = Faker::Lorem @standard_wordlist = I18n.translate('faker.lorem.words') @@ -34,13 +33,13 @@ def test_characters_with_args # Words delivered by a standard request should be on the standard wordlist. def test_standard_words @words = @tester.words(1000) - @words.each {|w| assert @standard_wordlist.include?(w) } + @words.each { |w| assert @standard_wordlist.include?(w) } end # Words requested from the supplemental list should all be in that list. def test_supplemental_words - @words = @tester.words(10000, true) - @words.each {|w| assert @complete_wordlist.include?(w) } + @words = @tester.words(10_000, true) + @words.each { |w| assert @complete_wordlist.include?(w) } end # Faker::Lorem.word generates random word from standart wordlist @@ -67,10 +66,10 @@ def test_range_count_param ss = @tester.sentences(2..5) ps = @tester.paragraphs(2..5) - assert(2 <= cs.length && cs.length <= 5) - assert(2 <= ws.length && ws.length <= 5) - assert(2 <= ss.length && ss.length <= 5) - assert(2 <= ps.length && ps.length <= 5) + assert(cs.length >= 2 && cs.length <= 5) + assert(ws.length >= 2 && ws.length <= 5) + assert(ss.length >= 2 && ss.length <= 5) + assert(ps.length >= 2 && ps.length <= 5) end def test_exclusive_range_count_param @@ -86,10 +85,10 @@ def test_exclusive_range_count_param end def test_array_count_param - cs = @tester.characters([1,4]) - ws = @tester.words([1,4]) - ss = @tester.sentences([1,4]) - ps = @tester.paragraphs([1,4]) + cs = @tester.characters([1, 4]) + ws = @tester.words([1, 4]) + ss = @tester.sentences([1, 4]) + ps = @tester.paragraphs([1, 4]) assert(cs.length == 1 || cs.length == 4) assert(ws.length == 1 || ws.length == 4) @@ -103,7 +102,7 @@ def test_words_with_large_count_params array = @tester.words([250, 500]) assert(exact.length == 500) - assert(250 <= range.length && range.length <= 500) + assert(range.length >= 250 && range.length <= 500) assert(array.length == 250 || array.length == 500) end end diff --git a/test/test_faker_lovecraft.rb b/test/test_faker_lovecraft.rb index 010b9972cc..3c6afe2977 100644 --- a/test/test_faker_lovecraft.rb +++ b/test/test_faker_lovecraft.rb @@ -1,7 +1,6 @@ require File.dirname(__FILE__) + '/test_helper.rb' class TestFakerLovecraft < Test::Unit::TestCase - def setup @tester = Faker::Lovecraft @wordlist = I18n.translate('faker.lovecraft.words') @@ -40,15 +39,15 @@ def test_range_count_param ss = @tester.sentences(2..5) ps = @tester.paragraphs(2..5) - assert(2 <= ws.length && ws.length <= 5) - assert(2 <= ss.length && ss.length <= 5) - assert(2 <= ps.length && ps.length <= 5) + assert(ws.length >= 2 && ws.length <= 5) + assert(ss.length >= 2 && ss.length <= 5) + assert(ps.length >= 2 && ps.length <= 5) end def test_array_count_param - ws = @tester.words([1,4]) - ss = @tester.sentences([1,4]) - ps = @tester.paragraphs([1,4]) + ws = @tester.words([1, 4]) + ss = @tester.sentences([1, 4]) + ps = @tester.paragraphs([1, 4]) assert(ws.length == 1 || ws.length == 4) assert(ss.length == 1 || ss.length == 4) @@ -61,7 +60,7 @@ def test_words_with_large_count_params array = @tester.words([250, 500]) assert(exact.length == 500) - assert(250 <= range.length && range.length <= 500) + assert(range.length >= 250 && range.length <= 500) assert(array.length == 250 || array.length == 500) end diff --git a/test/test_faker_markdown.rb b/test/test_faker_markdown.rb index eeb83a6756..f52a7a620e 100644 --- a/test/test_faker_markdown.rb +++ b/test/test_faker_markdown.rb @@ -15,7 +15,7 @@ def test_headers def test_emphasis test_trigger = @tester.emphasis.split('') - assert(test_trigger.to_set.intersect?(["_", "~", "*", "**"].to_set)) + assert(test_trigger.to_set.intersect?(['_', '~', '*', '**'].to_set)) end def test_ordered_list @@ -34,26 +34,26 @@ def test_unordered_list test_trigger = @tester.unordered_list.split("\n") test_trigger.each do |line| - assert_equal("*", line[0]) + assert_equal('*', line[0]) end end def test_inline_code test_trigger = @tester.inline_code.split('') - assert_equal(test_trigger.first, "`") - assert_equal(test_trigger.last, "`") + assert_equal(test_trigger.first, '`') + assert_equal(test_trigger.last, '`') end def test_block_code test_trigger = @tester.block_code.split('') - assert_equal(test_trigger[0], "`") - assert_equal(test_trigger[1], "`") - assert_equal(test_trigger[2], "`") - assert_equal(test_trigger[-1], "`") - assert_equal(test_trigger[-2], "`") - assert_equal(test_trigger[-3], "`") + assert_equal(test_trigger[0], '`') + assert_equal(test_trigger[1], '`') + assert_equal(test_trigger[2], '`') + assert_equal(test_trigger[-1], '`') + assert_equal(test_trigger[-2], '`') + assert_equal(test_trigger[-3], '`') end def test_table @@ -63,7 +63,7 @@ def test_table assert_instance_of(String, table_data) end assert_equal(test_trigger.length, 4) - assert_equal(test_trigger[1], "---- | ---- | ----") + assert_equal(test_trigger[1], '---- | ---- | ----') end def test_random @@ -71,5 +71,4 @@ def test_random assert_instance_of(String, test_trigger) end - end diff --git a/test/test_faker_measurement.rb b/test/test_faker_measurement.rb index a8b369c97f..e510ef7466 100644 --- a/test/test_faker_measurement.rb +++ b/test/test_faker_measurement.rb @@ -14,8 +14,8 @@ def length end def volume - singular_unit = @tester.volume("none") - plural_unit = @tester.volume("all") + singular_unit = @tester.volume('none') + plural_unit = @tester.volume('all') custom_amount_float = @tester.volume(1.5) custom_amount_integer = @tester.volume(276) @@ -47,7 +47,7 @@ def metric_weight end def test_invalid_amount_error - amount = "hello world!" + amount = 'hello world!' assert_raise ArgumentError do @tester.volume(amount) diff --git a/test/test_faker_michael_scott.rb b/test/test_faker_michael_scott.rb index 1d8c7b1b19..2579dad210 100644 --- a/test/test_faker_michael_scott.rb +++ b/test/test_faker_michael_scott.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerMichaelScott < Test::Unit::TestCase - def setup @tester = Faker::MichaelScott end @@ -9,4 +8,4 @@ def setup def test_quote assert @tester.quote.match(/\w+/) end -end \ No newline at end of file +end diff --git a/test/test_faker_movie.rb b/test/test_faker_movie.rb index b7e81e80d3..c5c06addb5 100644 --- a/test/test_faker_movie.rb +++ b/test/test_faker_movie.rb @@ -1,13 +1,12 @@ - require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') +require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') - class TestFakerMovie < Test::Unit::TestCase +class TestFakerMovie < Test::Unit::TestCase + def setup + @tester = Faker::Movie + end - def setup - @tester = Faker::Movie - end - - def test_quote - assert @tester.quote.match(/\w+/) - end - end + def test_quote + assert @tester.quote.match(/\w+/) + end +end diff --git a/test/test_faker_music.rb b/test/test_faker_music.rb index 91fd5d94e8..85120a2cfa 100644 --- a/test/test_faker_music.rb +++ b/test/test_faker_music.rb @@ -8,14 +8,14 @@ def setup def test_keys assert @tester.keys.size == 7 @tester.keys.each do |key| - refute key.to_s.empty? + refute key.to_s.empty? end end def test_key_variants assert @tester.key_variants.size == 3 @tester.key_variants.each do |key_variant| - refute key_variant.nil? + refute key_variant.nil? end end diff --git a/test/test_faker_name.rb b/test/test_faker_name.rb index a0696d307a..e7e4e5b446 100644 --- a/test/test_faker_name.rb +++ b/test/test_faker_name.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerName < Test::Unit::TestCase - def setup @tester = Faker::Name end @@ -33,7 +32,7 @@ def test_suffix def test_job_titles @job_titles = Faker::Name.job_titles @job_titles.each do |title| - refute title.to_s.empty? + refute title.to_s.empty? end end diff --git a/test/test_faker_nation.rb b/test/test_faker_nation.rb index 352e61b5bf..94adca25e5 100644 --- a/test/test_faker_nation.rb +++ b/test/test_faker_nation.rb @@ -1,17 +1,15 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerNation < Test::Unit::TestCase - def setup @tester = Faker::Nation end - + def test_nationality assert @tester.nationality.match(/(\w+\.? ?){2,3}/) end - + def test_language assert @tester.language.match(/[A-Z][a-z]+\.?/) end - end diff --git a/test/test_faker_number.rb b/test/test_faker_number.rb index f42fc0ed4c..9f5afc8632 100644 --- a/test/test_faker_number.rb +++ b/test/test_faker_number.rb @@ -16,7 +16,7 @@ def test_number assert @tester.number(10).length == 10 assert @tester.number(1).length == 1 - assert @tester.number(0) == "" + assert @tester.number(0) == '' end def test_decimal @@ -26,12 +26,12 @@ def test_decimal def test_digit assert @tester.digit.match(/[0-9]{1}/) - assert (1..1000).collect {|i| @tester.digit == "9"}.include?(true) + assert((1..1000).collect { |_i| @tester.digit == '9' }.include?(true)) end def test_even_distribution assert stats = {} - assert times = 10000 + assert times = 10_000 times.times do assert num = @tester.digit @@ -39,16 +39,16 @@ def test_even_distribution assert stats[num] += 1 end - stats.each do |k, v| + stats.each do |_k, v| assert_in_delta 10.0, 100.0 * v / times, 2.0 end end def test_normal - n = 10000 - values = n.times.map { @tester.normal(150.0, 100.0) } + n = 10_000 + values = Array.new(n) { @tester.normal(150.0, 100.0) } mean = values.reduce(:+) / n.to_f - variance = values.inject(0) { |var, value| var + (value - mean) ** 2 } / (n - 1).to_f + variance = values.inject(0) { |var, value| var + (value - mean)**2 } / (n - 1).to_f std_dev = Math.sqrt variance assert_in_delta 150.0, mean, 5.0 @@ -106,12 +106,12 @@ def test_insignificant_zero @tester.stub :digit, 0 do assert_equal '0', @tester.number(1) 100.times do - assert_match (/^[1-9]0/), @tester.number(2) + assert_match(/^[1-9]0/, @tester.number(2)) end - assert_equal '0.0', @tester.decimal(1,1) + assert_equal '0.0', @tester.decimal(1, 1) 100.times do - assert_match (/^0\.0[1-9]/), @tester.decimal(1,2) + assert_match(/^0\.0[1-9]/, @tester.decimal(1, 2)) end end end diff --git a/test/test_faker_omniauth.rb b/test/test_faker_omniauth.rb index 3d0067f246..87e3905b1f 100644 --- a/test/test_faker_omniauth.rb +++ b/test/test_faker_omniauth.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerInternetOmniauth < Test::Unit::TestCase - def setup @tester = Faker::Omniauth end @@ -16,7 +15,7 @@ def test_omniauth_google plus_url = "https://plus.google.com/#{auth[:uid]}" openid_id = "https://www.google.com/accounts/o8/id?id=#{auth[:uid]}" - assert_equal "google_oauth2", provider + assert_equal 'google_oauth2', provider assert_equal 9, auth[:uid].length assert_equal 2, word_count(info[:name]) assert info[:email].match safe_email_regex(info[:first_name], info[:last_name]) @@ -25,13 +24,13 @@ def test_omniauth_google assert_instance_of String, info[:image] assert_instance_of String, credentials[:token] assert_instance_of String, credentials[:refresh_token] - + if RUBY_VERSION < '2.4.0' assert_instance_of Fixnum, credentials[:expires_at] else assert_instance_of Integer, credentials[:expires_at] end - + assert_equal true, credentials[:expires] assert_equal 9, extra_raw_info[:sub].length assert_equal info[:email], extra_raw_info[:email] @@ -41,20 +40,20 @@ def test_omniauth_google assert_equal info[:last_name], extra_raw_info[:family_name] assert_equal plus_url, extra_raw_info[:profile] assert_instance_of String, extra_raw_info[:picture] - assert is_gender?(extra_raw_info[:gender]) + assert gender?(extra_raw_info[:gender]) assert_instance_of String, extra_raw_info[:birthday] - assert_equal "en", extra_raw_info[:local] + assert_equal 'en', extra_raw_info[:local] assert_instance_of String, extra_raw_info[:hd] - assert_equal "accounts.google.com", id_info["iss"] - assert_instance_of String, id_info["at_hash"] - assert_instance_of String, id_info["email_verified"] - assert_equal 28, id_info["sub"].length - assert_equal "APP_ID", id_info["azp"] - assert_equal info[:email], id_info["email"] - assert_equal "APP_ID", id_info["aud"] - assert_instance_of String, id_info["iat"] - assert_instance_of String, id_info["exp"] - assert_equal openid_id, id_info["openid_id"] + assert_equal 'accounts.google.com', id_info['iss'] + assert_instance_of String, id_info['at_hash'] + assert_instance_of String, id_info['email_verified'] + assert_equal 28, id_info['sub'].length + assert_equal 'APP_ID', id_info['azp'] + assert_equal info[:email], id_info['email'] + assert_equal 'APP_ID', id_info['aud'] + assert_instance_of String, id_info['iat'] + assert_instance_of String, id_info['exp'] + assert_equal openid_id, id_info['openid_id'] end def test_omniauth_google_with_name @@ -63,7 +62,7 @@ def test_omniauth_google_with_name auth = @tester.google(name: custom_name) info = auth[:info] extra_raw_info = auth[:extra][:raw_info] - + assert_instance_of String, info[:name] assert_equal 2, word_count(info[:name]) assert_equal custom_name, info[:name] @@ -85,7 +84,7 @@ def test_omniauth_google_with_email assert_instance_of String, info[:email] assert_equal custom_email, info[:email] assert_equal custom_email, extra_raw_info[:email] - assert_equal custom_email, id_info["email"] + assert_equal custom_email, id_info['email'] end def test_omniauth_google_with_uid @@ -111,14 +110,14 @@ def test_omniauth_facebook location = extra_raw_info[:location] url = "http://www.facebook.com/#{username}" - assert_equal "facebook", provider + assert_equal 'facebook', provider assert_equal 7, uid.length assert info[:email].match safe_email_regex(info[:first_name], info[:last_name]) assert_equal 2, word_count(info[:name]) assert_instance_of String, info[:first_name] assert_instance_of String, info[:last_name] assert_instance_of String, info[:image] - assert is_boolean?(info[:verified]) + assert boolean?(info[:verified]) assert_instance_of String, credentials[:token] if RUBY_VERSION < '2.4.0' @@ -136,7 +135,7 @@ def test_omniauth_facebook assert_equal username, extra_raw_info[:username] assert_equal 9, location[:id].length assert_instance_of String, location[:name] - assert is_gender?(extra_raw_info[:gender]) + assert gender?(extra_raw_info[:gender]) assert_equal info[:email], extra_raw_info[:email] if RUBY_VERSION < '2.4.0' @@ -146,7 +145,7 @@ def test_omniauth_facebook end assert_instance_of String, extra_raw_info[:locale] - assert is_boolean?(extra_raw_info[:verified]) + assert boolean?(extra_raw_info[:verified]) assert_instance_of String, extra_raw_info[:updated_time] end @@ -219,9 +218,9 @@ def test_omniauth_twitter raw_info = auth[:extra][:raw_info] url = "https://twitter.com/#{info[:nickname]}" - assert_equal "twitter", provider + assert_equal 'twitter', provider assert_equal 6, uid.length - assert_equal info[:name].downcase.gsub(' ', ''), info[:nickname] + assert_equal info[:name].downcase.delete(' '), info[:nickname] assert_equal 2, word_count(info[:name]) assert_equal 2, info[:location].split(', ').length assert_instance_of String, info[:image] @@ -238,10 +237,10 @@ def test_omniauth_twitter else assert_instance_of Integer, raw_info[:listed_count] end - + assert_instance_of String, raw_info[:profile_sidebar_border_color] refute raw_info[:url] - assert_equal "en", raw_info[:lang] + assert_equal 'en', raw_info[:lang] if RUBY_VERSION < '2.4.0' assert_instance_of Fixnum, raw_info[:statuses_count] @@ -253,20 +252,20 @@ def test_omniauth_twitter assert_instance_of String, raw_info[:profile_background_image_url_https] assert_equal info[:location], raw_info[:location] assert_instance_of String, raw_info[:time_zone] - assert is_boolean?(raw_info[:follow_request_sent]) + assert boolean?(raw_info[:follow_request_sent]) assert_equal uid, raw_info[:id] - assert is_boolean?(raw_info[:profile_background_tile]) + assert boolean?(raw_info[:profile_background_tile]) assert_instance_of String, raw_info[:profile_sidebar_fill_color] - + if RUBY_VERSION < '2.4.0' assert_instance_of Fixnum, raw_info[:followers_count] else assert_instance_of Integer, raw_info[:followers_count] end - - assert is_boolean?(raw_info[:default_profile_image]) - assert_equal "", raw_info[:screen_name] - assert is_boolean?(raw_info[:following]) + + assert boolean?(raw_info[:default_profile_image]) + assert_equal '', raw_info[:screen_name] + assert boolean?(raw_info[:following]) if RUBY_VERSION < '2.4.0' assert_instance_of Fixnum, raw_info[:utc_offset] @@ -274,7 +273,7 @@ def test_omniauth_twitter assert_instance_of Integer, raw_info[:utc_offset] end - assert is_boolean?(raw_info[:verified]) + assert boolean?(raw_info[:verified]) if RUBY_VERSION < '2.4.0' assert_instance_of Fixnum, raw_info[:favourites_count] @@ -283,7 +282,7 @@ def test_omniauth_twitter end assert_instance_of String, raw_info[:profile_background_color] - assert is_boolean?(raw_info[:is_translator]) + assert boolean?(raw_info[:is_translator]) if RUBY_VERSION < '2.4.0' assert_instance_of Fixnum, raw_info[:friends_count] @@ -291,25 +290,25 @@ def test_omniauth_twitter assert_instance_of Integer, raw_info[:friends_count] end - assert is_boolean?(raw_info[:notifications]) - assert is_boolean?(raw_info[:geo_enabled]) + assert boolean?(raw_info[:notifications]) + assert boolean?(raw_info[:geo_enabled]) assert_instance_of String, raw_info[:profile_background_image_url] - assert is_boolean?(raw_info[:protected]) + assert boolean?(raw_info[:protected]) assert_equal info[:description], raw_info[:description] assert_instance_of String, raw_info[:profile_link_color] assert_instance_of String, raw_info[:created_at] assert_equal uid, raw_info[:id_str] assert_instance_of String, raw_info[:profile_image_url_https] - assert is_boolean?(raw_info[:default_profile]) - assert is_boolean?(raw_info[:profile_use_background_image]) + assert boolean?(raw_info[:default_profile]) + assert boolean?(raw_info[:profile_use_background_image]) assert_instance_of Array, raw_info[:entities][:description][:urls] assert_instance_of String, raw_info[:profile_text_color] - assert is_boolean?(raw_info[:contributors_enabled]) + assert boolean?(raw_info[:contributors_enabled]) end def test_omniauth_twitter_with_name custom_name = 'Happy Gilmore' - nickname = custom_name.downcase.gsub(' ', '') + nickname = custom_name.downcase.delete(' ') url = "https://twitter.com/#{nickname}" auth = @tester.twitter(name: custom_name) info = auth[:info] @@ -348,38 +347,38 @@ def test_omniauth_twitter_with_uid def test_omniauth_linkedin auth = @tester.linkedin - info = auth["info"] - credentials = auth["credentials"] - extra = auth["extra"] - access_token = extra["access_token"] - params = access_token["params"] - raw_info = extra["raw_info"] + info = auth['info'] + credentials = auth['credentials'] + extra = auth['extra'] + access_token = extra['access_token'] + params = access_token['params'] + raw_info = extra['raw_info'] first_name = info['first_name'].downcase last_name = info['last_name'].downcase url = "http://www.linkedin.com/in/#{first_name}#{last_name}" - assert_equal "linkedin", auth["provider"] - assert_equal 6, auth["uid"].length - assert_equal 2, word_count(info["name"]) + assert_equal 'linkedin', auth['provider'] + assert_equal 6, auth['uid'].length + assert_equal 2, word_count(info['name']) assert info['email'].match safe_email_regex(first_name, last_name) - assert_equal info["name"], info["nickname"] - assert_instance_of String, info["first_name"] - assert_instance_of String, info["last_name"] - assert_equal 2, info["location"].split(', ').count - assert_instance_of String, info["description"] - assert_instance_of String, info["image"] - assert_instance_of String, info["phone"] - assert_instance_of String, info["headline"] - assert_instance_of String, info["industry"] - assert_equal url, info["urls"]["public_profile"] - assert_instance_of String, credentials["token"] - assert_instance_of String, credentials["secret"] - assert_equal credentials["token"], access_token["token"] - assert_equal credentials["secret"], access_token["secret"] - refute access_token["consumer"] - assert_equal credentials["token"], params[:oauth_token] - assert_equal credentials["secret"], params[:oauth_token_secret] - + assert_equal info['name'], info['nickname'] + assert_instance_of String, info['first_name'] + assert_instance_of String, info['last_name'] + assert_equal 2, info['location'].split(', ').count + assert_instance_of String, info['description'] + assert_instance_of String, info['image'] + assert_instance_of String, info['phone'] + assert_instance_of String, info['headline'] + assert_instance_of String, info['industry'] + assert_equal url, info['urls']['public_profile'] + assert_instance_of String, credentials['token'] + assert_instance_of String, credentials['secret'] + assert_equal credentials['token'], access_token['token'] + assert_equal credentials['secret'], access_token['secret'] + refute access_token['consumer'] + assert_equal credentials['token'], params[:oauth_token] + assert_equal credentials['secret'], params[:oauth_token_secret] + if RUBY_VERSION < '2.4.0' assert_instance_of Fixnum, params[:oauth_expires_in] assert_instance_of Fixnum, params[:oauth_authorization_expires_in] @@ -388,16 +387,16 @@ def test_omniauth_linkedin assert_instance_of Integer, params[:oauth_authorization_expires_in] end - refute access_token["response"] - assert_equal info["first_name"], raw_info["firstName"] - assert_equal info["headline"], raw_info["headline"] - assert_equal auth["uid"], raw_info["id"] - assert_equal info["industry"], raw_info["industry"] - assert_equal info["last_name"], raw_info["lastName"] - assert_instance_of String, raw_info["location"]["country"]["code"] - assert_instance_of String, raw_info["location"]["name"] - assert_instance_of String, raw_info["pictureUrl"] - assert_equal info["urls"]["public_profile"], raw_info["publicProfileUrl"] + refute access_token['response'] + assert_equal info['first_name'], raw_info['firstName'] + assert_equal info['headline'], raw_info['headline'] + assert_equal auth['uid'], raw_info['id'] + assert_equal info['industry'], raw_info['industry'] + assert_equal info['last_name'], raw_info['lastName'] + assert_instance_of String, raw_info['location']['country']['code'] + assert_instance_of String, raw_info['location']['name'] + assert_instance_of String, raw_info['pictureUrl'] + assert_equal info['urls']['public_profile'], raw_info['publicProfileUrl'] end def test_omniauth_linkedin_with_name @@ -426,7 +425,7 @@ def test_omniauth_linkedin_with_email def test_omniauth_linkedin_with_uid custom_uid = '12345' auth = @tester.linkedin(uid: custom_uid) - extra_raw_info = auth['extra']['raw_info'] + extra_raw_info = auth['extra']['raw_info'] assert_instance_of String, auth['uid'] assert_equal custom_uid, auth['uid'] @@ -445,7 +444,7 @@ def test_omniauth_github html_url = "https://github.com/#{login}" api_url = "https://api.github.com/users/#{login}" - assert_equal "github", provider + assert_equal 'github', provider assert_equal 8, uid.length assert_equal uid, extra_raw_info[:id] assert info[:email].match safe_email_regex(info[:first_name], info[:last_name]) @@ -465,7 +464,7 @@ def test_omniauth_github assert_equal false, credentials[:expires] assert_instance_of String, extra_raw_info[:avatar_url] - assert_equal "", extra_raw_info[:gravatar_id] + assert_equal '', extra_raw_info[:gravatar_id] assert_equal api_url, extra_raw_info[:url] assert_equal html_url, extra_raw_info[:html_url] assert_equal "#{api_url}/followers", extra_raw_info[:followers_url] @@ -477,8 +476,8 @@ def test_omniauth_github assert_equal "#{api_url}/repos", extra_raw_info[:repos_url] assert_equal "#{api_url}/events{/privacy}", extra_raw_info[:events_url] assert_equal "#{api_url}/received_events", extra_raw_info[:received_events_url] - assert_equal "User", extra_raw_info[:type] - assert is_boolean?(extra_raw_info[:site_admin]) + assert_equal 'User', extra_raw_info[:type] + assert boolean?(extra_raw_info[:site_admin]) assert_equal nil, extra_raw_info[:company] assert_equal nil, extra_raw_info[:blog] assert_instance_of String, extra_raw_info[:location] @@ -543,12 +542,12 @@ def word_count(string) string.split(' ').length end - def is_boolean?(test) - !!test == test + def boolean?(test) + !test.nil? end - def is_gender?(test) - ["female", "male"].include?(test) + def gender?(test) + %w[female male].include?(test) end def safe_email_regex(f_name, l_name) diff --git a/test/test_faker_one_piece.rb b/test/test_faker_one_piece.rb index afd18030fa..7fe220325e 100644 --- a/test/test_faker_one_piece.rb +++ b/test/test_faker_one_piece.rb @@ -1,33 +1,32 @@ - require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') +require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') - class TestFakerOnePiece < Test::Unit::TestCase +class TestFakerOnePiece < Test::Unit::TestCase + def setup + @tester = Faker::OnePiece + end - def setup - @tester = Faker::OnePiece - end + def test_character + assert @tester.character.match(/\w+/) + end - def test_character - assert @tester.character.match(/\w+/) - end + def test_sea + assert @tester.sea.match(/\w+/) + end - def test_sea - assert @tester.sea.match(/\w+/) - end + def test_island + assert @tester.island.match(/\w+/) + end - def test_island - assert @tester.island.match(/\w+/) - end + def test_location + assert @tester.location.match(/\w+/) + end - def test_location - assert @tester.location.match(/\w+/) - end + def test_quote + assert @tester.quote.match(/\w+/) + end - def test_quote - assert @tester.quote.match(/\w+/) - end - - def test_akuma_no_mi - assert @tester.akuma_no_mi.match(/\w+/) - end - end + def test_akuma_no_mi + assert @tester.akuma_no_mi.match(/\w+/) + end +end diff --git a/test/test_faker_pokemon.rb b/test/test_faker_pokemon.rb index 3bf357db2a..590ffcdba4 100644 --- a/test/test_faker_pokemon.rb +++ b/test/test_faker_pokemon.rb @@ -16,6 +16,4 @@ def test_location def test_move assert @tester.move.match(/\w+/) end - - end diff --git a/test/test_faker_programming_language.rb b/test/test_faker_programming_language.rb index 4ad7799115..4e02c983ce 100644 --- a/test/test_faker_programming_language.rb +++ b/test/test_faker_programming_language.rb @@ -1,17 +1,15 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') - class TestFakerProgrammingLanguage < Test::Unit::TestCase - - def setup - @tester = Faker::ProgrammingLanguage - end - - def test_name - assert @tester.name.match(/\w/) - end - - def test_creator - assert @tester.creator.match(/\w/) - end - - end +class TestFakerProgrammingLanguage < Test::Unit::TestCase + def setup + @tester = Faker::ProgrammingLanguage + end + + def test_name + assert @tester.name.match(/\w/) + end + + def test_creator + assert @tester.creator.match(/\w/) + end +end diff --git a/test/test_faker_rock_band.rb b/test/test_faker_rock_band.rb index 4b83d3291e..62bac78c89 100644 --- a/test/test_faker_rock_band.rb +++ b/test/test_faker_rock_band.rb @@ -8,5 +8,4 @@ def setup def test_name assert @tester.name.match(/\w+/) end - -end \ No newline at end of file +end diff --git a/test/test_faker_science.rb b/test/test_faker_science.rb index 45ede8e874..e9aae03e22 100644 --- a/test/test_faker_science.rb +++ b/test/test_faker_science.rb @@ -12,5 +12,4 @@ def test_element def test_scientist assert @tester.scientist.match(/\w+/) end - end diff --git a/test/test_faker_seinfeld.rb b/test/test_faker_seinfeld.rb index 14920d904a..ced02777bc 100644 --- a/test/test_faker_seinfeld.rb +++ b/test/test_faker_seinfeld.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerSeinfeld < Test::Unit::TestCase - def setup @tester = Faker::Seinfeld end diff --git a/test/test_faker_shakespeare.rb b/test/test_faker_shakespeare.rb index ff7f5f615f..d18b1fbbc9 100644 --- a/test/test_faker_shakespeare.rb +++ b/test/test_faker_shakespeare.rb @@ -20,5 +20,4 @@ def test_romeo_and_juliet_quote def test_hamlet_quote assert @tester.hamlet_quote.match(/\w+/) end - end diff --git a/test/test_faker_simpsons.rb b/test/test_faker_simpsons.rb index 4ecc5d96eb..ca7517cca8 100644 --- a/test/test_faker_simpsons.rb +++ b/test/test_faker_simpsons.rb @@ -1,15 +1,12 @@ -#encoding: utf-8 -#frozen_string_literal: true +# frozen_string_literal: true require File.expand_path(File.dirname(__FILE__) + '/test_helper') class TestFakerSimpsons < Test::Unit::TestCase - def setup Faker::Config.locale = nil end - def test_characters 10.times { assert Faker::Simpsons.character.match(/[\w]+/) } end @@ -22,10 +19,8 @@ def test_quote 10.times { assert Faker::Simpsons.quote.match(/[\w]+/) } end - def test_locales - [nil,'en','de',#... - ].each do |locale_name| + [nil, 'en', 'de'].each do |_locale_name| Faker::Config.locale = 'de' assert Faker::Simpsons.character.is_a? String assert Faker::Simpsons.location .is_a? String diff --git a/test/test_faker_slack_emoji.rb b/test/test_faker_slack_emoji.rb index 273e77b476..bd2459ba6c 100644 --- a/test/test_faker_slack_emoji.rb +++ b/test/test_faker_slack_emoji.rb @@ -1,10 +1,9 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerSlackEmoji < Test::Unit::TestCase - def setup @tester = Faker::SlackEmoji - @emoticon_regex= /^:([\w-]+):$/ + @emoticon_regex = /^:([\w-]+):$/ end def test_people @@ -42,4 +41,4 @@ def test_custom def test_emoji assert @tester.emoji.match(@emoticon_regex) end -end \ No newline at end of file +end diff --git a/test/test_faker_star_wars.rb b/test/test_faker_star_wars.rb index 742d835dec..d0a74f7896 100644 --- a/test/test_faker_star_wars.rb +++ b/test/test_faker_star_wars.rb @@ -27,18 +27,18 @@ def test_quote # test good match def test_random_character_quote - assert @tester.quote("admiral_ackbar").match(/\w+/) + assert @tester.quote('admiral_ackbar').match(/\w+/) end # test good alternate spelling match def test_random_character_alt_spelling_quote - assert @tester.quote("ackbar").match(/\w+/) + assert @tester.quote('ackbar').match(/\w+/) end # test error on no match def test_invalid_quote assert_raise ArgumentError do - @tester.quote("Leto Atreides") + @tester.quote('Leto Atreides') end end diff --git a/test/test_faker_street.rb b/test/test_faker_street.rb index 7866df8f23..be49bd9ced 100644 --- a/test/test_faker_street.rb +++ b/test/test_faker_street.rb @@ -4,24 +4,26 @@ class TestFakerStreet < Test::Unit::TestCase def setup @tester = Faker::Address @old_locales = I18n.config.available_locales + # rubocop:disable Lint/InterpolationCheck shire = { - :faker => { - :address => { - :street_name => ['#{street_prefix} #{street_root} #{street_suffix}'], - :street_prefix => ['Wide'], - :street_root => ['Cheerful'], - :street_suffix => ['Path'], - :secondary_address => ['(Green Door)'], - :street_address => ['#{street_name} #{building_number}'], - :building_number => ['#'], - :community_prefix => ['Pine'], - :community_suffix => ['Place'], - :time_zone => ['Pacific/Pago_Pago'], + faker: { + address: { + street_name: ['#{street_prefix} #{street_root} #{street_suffix}'], + street_prefix: ['Wide'], + street_root: ['Cheerful'], + street_suffix: ['Path'], + secondary_address: ['(Green Door)'], + street_address: ['#{street_name} #{building_number}'], + building_number: ['#'], + community_prefix: ['Pine'], + community_suffix: ['Place'], + time_zone: ['Pacific/Pago_Pago'] } } } + # rubocop:enable Lint/InterpolationCheck I18n.backend.store_translations(:shire, shire) - I18n.config.available_locales += [ :shire ] + I18n.config.available_locales += [:shire] end def teardown @@ -69,5 +71,4 @@ def test_full_address assert_match(/^(.+\s)?\d+ [\w'\s]+\, [\w'\s]+\, [\w']+ \d+/, @tester.full_address) end end - end diff --git a/test/test_faker_string.rb b/test/test_faker_string.rb index 540f4e304f..bf115b1610 100644 --- a/test/test_faker_string.rb +++ b/test/test_faker_string.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerString < Test::Unit::TestCase @@ -11,7 +12,7 @@ def teardown end def test_is_string - assert ::String === @tester.random + assert @tester.random.is_a?(String) end def test_has_valid_encoding @@ -28,11 +29,11 @@ def test_default_length end def test_nil_is_zero - 2.times { assert @tester.random(nil).length == 0 } + 2.times { assert @tester.random(nil).empty? } end def test_int_length - [0, -1, 1, rand(500), rand(4096)- 2048].each do |len| + [0, -1, 1, rand(500), rand(-2048..2047)].each do |len| 8.times { assert @tester.random(len).length == [0, len].max } end end @@ -49,7 +50,7 @@ def test_array_length array = [0, -1, 1, 1024, rand(2048)] 8.times { assert array.include? @tester.random(array).length } - num = rand(4096)- 2048 + num = rand(-2048..2047) array = [num, num, num] 8.times { assert @tester.random(array).length == [0, num].max } end @@ -58,6 +59,6 @@ def test_nested_lengths test = lambda do @tester.random([1, (2..5), [3, (-7...6)], nil]) end - 16.times { assert ((0..5).include? test.call.length) } + 16.times { assert(((0..5).cover? test.call.length)) } end end diff --git a/test/test_faker_stripe.rb b/test/test_faker_stripe.rb index bea849420d..602a377c38 100644 --- a/test/test_faker_stripe.rb +++ b/test/test_faker_stripe.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerStripe < Test::Unit::TestCase - def setup @tester = Faker::Stripe end @@ -11,7 +10,7 @@ def test_valid_card end def test_specific_valid_card - assert @tester.valid_card("visa").match(/\A\d{16}\z/) + assert @tester.valid_card('visa').match(/\A\d{16}\z/) end def test_invalid_card @@ -19,7 +18,7 @@ def test_invalid_card end def test_specific_error_invalid_card - assert @tester.invalid_card("zipFail").match(/\w+/) + assert @tester.invalid_card('zipFail').match(/\w+/) end def test_valid_exp_mo @@ -35,7 +34,6 @@ def test_valid_ccv end def test_valid_amex_ccv - assert @tester.ccv("amex").match(/\A\d{4}\z/) + assert @tester.ccv('amex').match(/\A\d{4}\z/) end end - diff --git a/test/test_faker_superhero.rb b/test/test_faker_superhero.rb index e95a1dd608..139881a540 100644 --- a/test/test_faker_superhero.rb +++ b/test/test_faker_superhero.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerSuperhero < Test::Unit::TestCase - def setup @tester = Faker::Superhero end diff --git a/test/test_faker_team.rb b/test/test_faker_team.rb index c6be01bf1f..63925a9b80 100644 --- a/test/test_faker_team.rb +++ b/test/test_faker_team.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerTeam < Test::Unit::TestCase - def setup @tester = Faker::Team end @@ -21,5 +20,4 @@ def test_state def test_sport assert @tester.sport.match(/(\w+){1}/) end - end diff --git a/test/test_faker_time.rb b/test/test_faker_time.rb index 6df4389fda..aa45a8bfba 100755 --- a/test/test_faker_time.rb +++ b/test/test_faker_time.rb @@ -1,7 +1,7 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerTime < Test::Unit::TestCase - TEN_HOURS = 36000 + TEN_HOURS = 36_000 def setup @tester = Faker::Time @@ -10,23 +10,23 @@ def setup def test_between_with_time_parameters from = Time.at(0) - to = Time.at(2145945600) + to = Time.at(2_145_945_600) 100.times do random_time = @tester.between(from, to) assert random_time >= from, "Expected >= \"#{from}\", but got #{random_time}" - assert random_time <= to , "Expected <= \"#{to}\", but got #{random_time}" + assert random_time <= to, "Expected <= \"#{to}\", but got #{random_time}" end end def test_between_with_date_parameters from = Time.at(0).to_date - to = Time.at(2145945600).to_date + to = Time.at(2_145_945_600).to_date 100.times do random_time = @tester.between(from, to) assert random_time.to_date >= from, "Expected >= \"#{from}\", but got #{random_time}" - assert random_time.to_date <= to , "Expected <= \"#{to}\", but got #{random_time}" + assert random_time.to_date <= to, "Expected <= \"#{to}\", but got #{random_time}" end end @@ -61,7 +61,7 @@ def test_return_type random_backward = @tester.backward(5) random_between_dates = @tester.between(Date.today, Date.today + 5) random_between_times = @tester.between(Time.now, Time.now + TEN_HOURS) - random_forward = @tester.forward(5) + random_forward = @tester.forward(5) [ random_backward, @@ -80,22 +80,22 @@ def test_format 100.times do period = @time_ranges.keys.to_a.sample - random_backward = @tester.backward(30,period, format) - random_between = @tester.between(from,to,period, format) - random_forward = @tester.forward(30,period, format) + random_backward = @tester.backward(30, period, format) + random_between = @tester.between(from, to, period, format) + random_forward = @tester.forward(30, period, format) [random_backward, random_between, random_forward].each do |result| - assert result.is_a?(String), "Expected a String, but got #{result.class}" - assert_nothing_raised "Not a valid date string" do - date_format = "%m/%d/%Y %I:%M %p" - DateTime.strptime(result, date_format) - end + assert result.is_a?(String), "Expected a String, but got #{result.class}" + assert_nothing_raised 'Not a valid date string' do + date_format = '%m/%d/%Y %I:%M %p' + DateTime.strptime(result, date_format) + end end end end def test_time_period from = Time.at(0).to_date - to = Time.at(2145945600).to_date + to = Time.at(2_145_945_600).to_date 100.times do period = @time_ranges.keys.to_a.sample @@ -106,7 +106,7 @@ def test_time_period random_forward = @tester.forward(30, period) [random_backward, random_between, random_forward].each_with_index do |result, index| - assert period_range.include?(result.hour.to_i), "#{[:random_backward, :random_between, :random_forward][index]}: \"#{result}\" expected to be included in Faker::Time::TIME_RANGES[:#{period}] range" + assert period_range.include?(result.hour.to_i), "#{%i[random_backward random_between random_forward][index]}: \"#{result}\" expected to be included in Faker::Time::TIME_RANGES[:#{period}] range" end end @@ -117,7 +117,7 @@ def test_time_period period = :between random_between = @tester.between(from, to, period) assert random_between >= from, "Expected >= \"#{from}\", but got #{random_between}" - assert random_between <= to , "Expected <= \"#{to}\", but got #{random_between}" + assert random_between <= to, "Expected <= \"#{to}\", but got #{random_between}" end end end diff --git a/test/test_faker_twin_peaks.rb b/test/test_faker_twin_peaks.rb index d5054657ae..eb01d18a67 100644 --- a/test/test_faker_twin_peaks.rb +++ b/test/test_faker_twin_peaks.rb @@ -15,5 +15,5 @@ def test_location def test_quote assert @tester.quote.match(/\w+/) - end + end end diff --git a/test/test_faker_types.rb b/test/test_faker_types.rb index ed75c226a4..782d295b64 100644 --- a/test/test_faker_types.rb +++ b/test/test_faker_types.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerTypes < Test::Unit::TestCase - module TestModule end @@ -14,9 +13,9 @@ def test_string_is_or_correct_type end def test_string_returns_correct_number_of_words - assert @tester.string(1).split(" ").length == 1 - assert @tester.string(5).split(" ").length == 5 - assert @tester.string(0).split(" ").length == 0 + assert @tester.string(1).split(' ').length == 1 + assert @tester.string(5).split(' ').length == 5 + assert @tester.string(0).split(' ').empty? end def test_character @@ -43,11 +42,9 @@ def test_hash_returns_a_hash end def test_hash_returns_the_correct_number_of_keys - key_count = 3 assert @tester.hash(3).keys.length == 3 - key_count = 0 - assert @tester.hash(0).keys.length == 0 - assert @tester.hash().keys.length == 1 + assert @tester.hash(0).keys.empty? + assert @tester.hash.keys.length == 1 end def test_complex_hash_returns_a_hash @@ -56,8 +53,8 @@ def test_complex_hash_returns_a_hash def test_complex_hash_returns_the_correct_number_of_keys assert @tester.complex_hash(3).keys.length == 3 - assert @tester.complex_hash(0).keys.length == 0 - assert @tester.complex_hash().keys.length == 1 + assert @tester.complex_hash(0).keys.empty? + assert @tester.complex_hash.keys.length == 1 end def test_array_returns_array @@ -65,16 +62,14 @@ def test_array_returns_array end def test_array_has_the_right_array - len = 3 assert @tester.array(3).length == 3 - len = 0 - assert @tester.array(0).length == 0 - assert @tester.array().length == 1 + assert @tester.array(0).empty? + assert @tester.array.length == 1 end def test_titleize - val = "foobar" - expected = "Foobar" + val = 'foobar' + expected = 'Foobar' assert @tester.send(:titleize, val) == expected end end diff --git a/test/test_faker_umphreys_mcgee.rb b/test/test_faker_umphreys_mcgee.rb index 2866df14b5..66ef5312a6 100644 --- a/test/test_faker_umphreys_mcgee.rb +++ b/test/test_faker_umphreys_mcgee.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerUmphreysMcgee < Test::Unit::TestCase - def setup @tester = Faker::UmphreysMcgee end diff --git a/test/test_faker_unique_generator.rb b/test/test_faker_unique_generator.rb index 5409f2f3a7..1ea1c8c6a6 100644 --- a/test/test_faker_unique_generator.rb +++ b/test/test_faker_unique_generator.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerUniqueGenerator < Test::Unit::TestCase - def test_generates_unique_values generator = Faker::UniqueGenerator.new(Faker::Base, 10_000) diff --git a/test/test_faker_university.rb b/test/test_faker_university.rb index 684e3b4067..16d5650f84 100644 --- a/test/test_faker_university.rb +++ b/test/test_faker_university.rb @@ -33,7 +33,4 @@ def test_greek_organization_is_assembled_from_greek_alphabet assert @alphabet.include?(letter) end end - - - end diff --git a/test/test_faker_vehicle.rb b/test/test_faker_vehicle.rb index dab2f5ab3d..2bc336d9a9 100644 --- a/test/test_faker_vehicle.rb +++ b/test/test_faker_vehicle.rb @@ -21,24 +21,23 @@ def test_manufacture end def test_flexible_key - flexible_key = @tester.instance_variable_get("@flexible_key") + flexible_key = @tester.instance_variable_get('@flexible_key') assert flexible_key == :vehicle end private - def transliterate(character) - @vin_chars.index(character) % 10 - end - - def calculate_vin_weight(character, i) - transliterate(character) * @vin_map.index(@vin_weights[i]) - end + def transliterate(character) + @vin_chars.index(character) % 10 + end - def vin_checksum(vin) - checksum_index = vin.split('').each_with_index.map(&method(:calculate_vin_weight)).inject(:+) - @vin_map[checksum_index % 11] - end + def calculate_vin_weight(character, idx) + transliterate(character) * @vin_map.index(@vin_weights[idx]) + end + def vin_checksum(vin) + checksum_index = vin.split('').each_with_index.map(&method(:calculate_vin_weight)).inject(:+) + @vin_map[checksum_index % 11] + end end diff --git a/test/test_faker_venture_bros.rb b/test/test_faker_venture_bros.rb index fb1b4aaa1f..f6b54d06ad 100644 --- a/test/test_faker_venture_bros.rb +++ b/test/test_faker_venture_bros.rb @@ -1,7 +1,6 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerVentureBros < Test::Unit::TestCase - def setup @tester = Faker::VentureBros end diff --git a/test/test_faker_verb.rb b/test/test_faker_verb.rb index f5ae065958..1acf0286c5 100644 --- a/test/test_faker_verb.rb +++ b/test/test_faker_verb.rb @@ -24,5 +24,4 @@ def test_simple_present def test_ing_form assert @tester.ing_form.match(/\w+/) end - end diff --git a/test/test_faker_witcher.rb b/test/test_faker_witcher.rb index 2bd89c6bbf..4f52eae0cb 100644 --- a/test/test_faker_witcher.rb +++ b/test/test_faker_witcher.rb @@ -22,11 +22,10 @@ def test_witcher end def test_monster - assert @witcher.monster.match(/\w+/) + assert @witcher.monster.match(/\w+/) end def test_quote - assert @witcher.quote.match(/\w+/) + assert @witcher.quote.match(/\w+/) end - -end \ No newline at end of file +end diff --git a/test/test_faker_zip_code.rb b/test/test_faker_zip_code.rb index b29f132102..94e4f0a8c7 100644 --- a/test/test_faker_zip_code.rb +++ b/test/test_faker_zip_code.rb @@ -2,25 +2,25 @@ class TestFakerZipCode < Test::Unit::TestCase def setup - @zip_codes_without_state = ['50817', '48666', '55551', '14242', '99852'] - @zip_codes_with_state = ['55555', '44444', '33333', '22222', '11111'] + @zip_codes_without_state = %w[50817 48666 55551 14242 99852] + @zip_codes_with_state = %w[55555 44444 33333 22222 11111] @old_locales = I18n.config.available_locales locale_without_state = { - :faker => { - :address => { - :state_abbreviation => [''], - :postcode => @zip_codes_without_state + faker: { + address: { + state_abbreviation: [''], + postcode: @zip_codes_without_state } } } locale_with_state = { - :faker => { - :address => { - :postcode_by_state => { - :NY => @zip_codes_with_state + faker: { + address: { + postcode_by_state: { + NY: @zip_codes_with_state } } } @@ -28,7 +28,7 @@ def setup I18n.backend.store_translations(:xy, locale_without_state) I18n.backend.store_translations(:xz, locale_with_state) - I18n.config.available_locales += [:xy, :xz] + I18n.config.available_locales += %i[xy xz] @tester = Faker::Address end diff --git a/test/test_flexible.rb b/test/test_flexible.rb index e498967ef3..2e2465bf78 100644 --- a/test/test_flexible.rb +++ b/test/test_flexible.rb @@ -7,14 +7,13 @@ class Foodie < Base end class TestFlexible < Test::Unit::TestCase - def setup @old_locales = I18n.config.available_locales - I18n.backend.store_translations(:xx, :faker => {:chow => {:yummie => [:fudge, :chocolate, :caramel], :taste => "delicious"}}) - I18n.backend.store_translations(:home, :faker => {:address => {:birthplace => [:bed, :hospital, :airplane]}}) - I18n.backend.store_translations(:kindergarden, :faker => {:name => {:girls_name => [:alice, :cheryl, :tatiana]}}) - I18n.backend.store_translations(:work, :faker => {:company => {:do_stuff => [:work, :work, :work]}}) - I18n.config.available_locales += [ :xx, :home, :kindergarden, :work ] + I18n.backend.store_translations(:xx, faker: { chow: { yummie: %i[fudge chocolate caramel], taste: 'delicious' } }) + I18n.backend.store_translations(:home, faker: { address: { birthplace: %i[bed hospital airplane] } }) + I18n.backend.store_translations(:kindergarden, faker: { name: { girls_name: %i[alice cheryl tatiana] } }) + I18n.backend.store_translations(:work, faker: { company: { do_stuff: %i[work work work] } }) + I18n.config.available_locales += %i[xx home kindergarden work] end def teardown @@ -24,13 +23,13 @@ def teardown def test_flexible_multiple_values I18n.with_locale(:xx) do actual = Faker::Foodie.yummie - assert [:fudge, :chocolate, :caramel].include? actual + assert %i[fudge chocolate caramel].include? actual end end def test_flexible_single_value I18n.with_locale(:xx) do - assert_equal "delicious", Faker::Foodie.taste + assert_equal 'delicious', Faker::Foodie.taste end end @@ -44,13 +43,13 @@ def test_raises_no_method_error def test_address_is_flexible I18n.with_locale(:home) do - assert [:bed, :hospital, :airplane].include? Faker::Address.birthplace + assert %i[bed hospital airplane].include? Faker::Address.birthplace end end def test_name_is_flexible I18n.with_locale(:kindergarden) do - assert [:alice, :cheryl, :tatiana].include? Faker::Name.girls_name + assert %i[alice cheryl tatiana].include? Faker::Name.girls_name end end diff --git a/test/test_fr_locale.rb b/test/test_fr_locale.rb index 5316dfde3d..382b9bcb0d 100644 --- a/test/test_fr_locale.rb +++ b/test/test_fr_locale.rb @@ -42,12 +42,12 @@ def test_fr_gb_methods end def test_fr_phone_format - phone = Faker::PhoneNumber.phone_number.gsub(/\D/,'') + phone = Faker::PhoneNumber.phone_number.gsub(/\D/, '') assert_match(/^(0|33)([1-5]|[8-9])\d{8}$/, phone) end def test_fr_cell_phone_format - mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/,'') + mobile = Faker::PhoneNumber.cell_phone.gsub(/\D/, '') assert_match(/^(0|33)(6|7)\d{8}$/, mobile) end diff --git a/test/test_helper.rb b/test/test_helper.rb index 49a2058bcf..634c3ea32a 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -27,8 +27,10 @@ def deterministically_verify(subject_proc, depth: 2, random: nil) raise 'need block' unless block_given? - depth.times.inject([]) { |results, index| + # rubocop:disable Style/MultilineBlockChain + depth.times.inject([]) do |results, _index| Faker::Config.random = random || Random.new(42) results << subject_proc.call.freeze.tap { |s| yield(s) } - }.repeated_combination(2) { |(first, second)| assert_equal first, second } + end.repeated_combination(2) { |(first, second)| assert_equal first, second } + # rubocop:enable Style/MultilineBlockChain end diff --git a/test/test_ko_locale.rb b/test/test_ko_locale.rb index 2bed952e2d..e8faa99db6 100644 --- a/test/test_ko_locale.rb +++ b/test/test_ko_locale.rb @@ -26,5 +26,4 @@ def test_ko_methods assert Faker::Name.first_name.is_a? String assert Faker::Name.name.is_a? String end - end diff --git a/test/test_locale.rb b/test/test_locale.rb index 2aa120a1df..3aa0fe62cc 100644 --- a/test/test_locale.rb +++ b/test/test_locale.rb @@ -1,8 +1,7 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') -LoadedYaml = ['en', 'en-BORK'].inject({}) do |h, locale| +LoadedYaml = ['en', 'en-BORK'].each_with_object({}) do |locale, h| h[locale] = YAML.load_file(File.expand_path(File.dirname(__FILE__) + "/../lib/locales/#{locale}.yml"))[locale]['faker'] - h end class TestLocale < Test::Unit::TestCase @@ -26,7 +25,7 @@ def test_configured_locale_translation def test_locale_override_when_calling_translate Faker::Config.locale = 'en-BORK' - assert_equal Faker::Base.translate('faker.separator', :locale => :en), LoadedYaml['en']['separator'] + assert_equal Faker::Base.translate('faker.separator', locale: :en), LoadedYaml['en']['separator'] end def test_translation_fallback diff --git a/test/test_lorem_pixel.rb b/test/test_lorem_pixel.rb index 63289be429..11a65916e3 100644 --- a/test/test_lorem_pixel.rb +++ b/test/test_lorem_pixel.rb @@ -6,15 +6,15 @@ def setup end def test_lorempixel - assert @tester.image.match(/https:\/\/lorempixel\.com\/(\d+\/\d+)/)[1] != nil + assert !@tester.image.match(%r{https:\/\/lorempixel\.com\/(\d+\/\d+)})[1].nil? end def test_lorempixel_insecure - assert @tester.image('300x300', nil, nil, nil, nil, secure: false).match(/http:\/\/lorempixel\.com\/(\d+\/\d+)/)[1] != nil + assert !@tester.image('300x300', nil, nil, nil, nil, secure: false).match(%r{http:\/\/lorempixel\.com\/(\d+\/\d+)})[1].nil? end def test_image_with_custom_size - assert @tester.image('3x3').match(/https:\/\/lorempixel\.com\/(\d+\/\d+)/)[1] == '3/3' + assert @tester.image('3x3').match(%r{https:\/\/lorempixel\.com\/(\d+\/\d+)})[1] == '3/3' end def test_image_with_incorrect_size @@ -24,11 +24,11 @@ def test_image_with_incorrect_size end def test_image_gray - assert @tester.image('300x300', true).match(/https:\/\/lorempixel\.com\/g\/\d+\/\d+/) + assert @tester.image('300x300', true).match(%r{https:\/\/lorempixel\.com\/g\/\d+\/\d+}) end def test_image_with_supported_category - assert @tester.image('300x300', false, 'animals').match(/https:\/\/lorempixel\.com\/\d+\/\d+\/(.*)/)[1] == 'animals' + assert @tester.image('300x300', false, 'animals').match(%r{https:\/\/lorempixel\.com\/\d+\/\d+\/(.*)})[1] == 'animals' end def test_image_with_incorrect_category @@ -38,7 +38,7 @@ def test_image_with_incorrect_category end def test_image_with_supported_category_and_correct_number - assert @tester.image('300x300', false, 'animals', 3).match(/https:\/\/lorempixel\.com\/\d+\/\d+\/.+\/(\d+)/)[1] == '3' + assert @tester.image('300x300', false, 'animals', 3).match(%r{https:\/\/lorempixel\.com\/\d+\/\d+\/.+\/(\d+)})[1] == '3' end def test_image_with_supported_category_and_incorrect_number @@ -54,11 +54,11 @@ def test_image_with_correct_number_and_without_category end def test_image_with_text_correct_number_and_supported_category - assert @tester.image('300x300', false, 'animals', 3, 'Dummy-text').match(/https:\/\/lorempixel\.com\/\d+\/\d+\/.+\/3\/(.+)/)[1] == 'Dummy-text' + assert @tester.image('300x300', false, 'animals', 3, 'Dummy-text').match(%r{https:\/\/lorempixel\.com\/\d+\/\d+\/.+\/3\/(.+)})[1] == 'Dummy-text' end def test_image_with_text_supported_category_and_text_without_number - assert @tester.image('300x300', false, 'animals', nil, 'Dummy-text').match(/https:\/\/lorempixel\.com\/\d+\/\d+\/.+\/(.+)/)[1] == 'Dummy-text' + assert @tester.image('300x300', false, 'animals', nil, 'Dummy-text').match(%r{https:\/\/lorempixel\.com\/\d+\/\d+\/.+\/(.+)})[1] == 'Dummy-text' end def test_image_with_text_without_number_and_category @@ -66,5 +66,4 @@ def test_image_with_text_without_number_and_category @tester.image('300x300', false, nil, nil, 'Dummy-text') end end - end diff --git a/test/test_pl_locale.rb b/test/test_pl_locale.rb index 61ad5653c8..14e63360e5 100644 --- a/test/test_pl_locale.rb +++ b/test/test_pl_locale.rb @@ -2,8 +2,8 @@ class TestPlLocale < Test::Unit::TestCase def setup - @phone_prefixes = %w{12 13 14 15 16 17 18 22 23 24 25 29 32 33 34 41 42 43 44 46 48 52 54 55 56 58 59 61 62 63 65 67 68 71 74 75 76 77 81 82 83 84 85 86 87 89 91 94 95}.sort - @cell_prefixes = %w{50 51 53 57 60 66 69 72 73 78 79 88}.sort + @phone_prefixes = %w[12 13 14 15 16 17 18 22 23 24 25 29 32 33 34 41 42 43 44 46 48 52 54 55 56 58 59 61 62 63 65 67 68 71 74 75 76 77 81 82 83 84 85 86 87 89 91 94 95].sort + @cell_prefixes = %w[50 51 53 57 60 66 69 72 73 78 79 88].sort @previous_locale = Faker::Config.locale Faker::Config.locale = :pl end @@ -14,16 +14,16 @@ def teardown def test_pl_names names = Faker::Base.fetch_all('name.first_name') + Faker::Base.fetch_all('name.last_name') - names.each { |name| assert_match(/([\wĄąĆćĘꣳÓ󌜯żŹź]+\.? ?){2,3}/,name)} + names.each { |name| assert_match(/([\wĄąĆćĘꣳÓ󌜯żŹź]+\.? ?){2,3}/, name) } end def test_pl_phone_number - prefixes = (0..999).map { Faker::PhoneNumber.phone_number[0,2] }.uniq.sort + prefixes = (0..999).map { Faker::PhoneNumber.phone_number[0, 2] }.uniq.sort assert_equal @phone_prefixes, prefixes end def test_pl_cell_phone - prefixes = (0..999).map { Faker::PhoneNumber.cell_phone[0,2] }.uniq.sort + prefixes = (0..999).map { Faker::PhoneNumber.cell_phone[0, 2] }.uniq.sort assert_equal @cell_prefixes, prefixes end diff --git a/test/test_placeholdit.rb b/test/test_placeholdit.rb index 57962695ba..afe8efabec 100644 --- a/test/test_placeholdit.rb +++ b/test/test_placeholdit.rb @@ -6,11 +6,11 @@ def setup end def test_placeholdit - assert @tester.image.match(/https:\/\/placehold\.it\/(.+)(png?)/)[1] != nil + assert !@tester.image.match(%r{https:\/\/placehold\.it\/(.+)(png?)})[1].nil? end def test_avatar_with_custom_size - assert @tester.image('3x3').match(/https:\/\/placehold\.it\/+(\d+x\d+)/)[1] == '3x3' + assert @tester.image('3x3').match(%r{https:\/\/placehold\.it\/+(\d+x\d+)})[1] == '3x3' end def test_avatar_with_incorrect_size @@ -20,7 +20,7 @@ def test_avatar_with_incorrect_size end def test_avatar_with_supported_format - assert @tester.image('300x300', 'jpg').match(/https:\/\/placehold\.it\/(.+)(jpg?)/) + assert @tester.image('300x300', 'jpg').match(%r{https:\/\/placehold\.it\/(.+)(jpg?)}) end def test_avatar_with_incorrect_format @@ -30,11 +30,11 @@ def test_avatar_with_incorrect_format end def test_avatar_background_with_correct_six_char_hex - assert @tester.image('300x300', 'jpg', 'ffffff').match(/https:\/\/placehold\.it\/(.+)(jpg?)\/ffffff/) + assert @tester.image('300x300', 'jpg', 'ffffff').match(%r{https:\/\/placehold\.it\/(.+)(jpg?)\/ffffff}) end def test_avatar_background_with_correct_three_char_hex - assert @tester.image('300x300', 'jpg', 'fff').match(/https:\/\/placehold\.it\/(.+)(jpg?)\/fff/) + assert @tester.image('300x300', 'jpg', 'fff').match(%r{https:\/\/placehold\.it\/(.+)(jpg?)\/fff}) end def test_avatar_background_with_wrong_six_char_hex @@ -56,11 +56,11 @@ def test_avatar_background_with_wrong_three_char_hex end def test_avatar_font_color_with_correct_six_char_hex - assert @tester.image('300x300', 'jpg', 'ffffff', '000000').match(/https:\/\/placehold\.it\/(.+)(jpg?)\/ffffff\/000000/) + assert @tester.image('300x300', 'jpg', 'ffffff', '000000').match(%r{https:\/\/placehold\.it\/(.+)(jpg?)\/ffffff\/000000}) end def test_avatar_font_color_with_correct_three_char_hex - assert @tester.image('300x300', 'jpg', 'fff', '000').match(/https:\/\/placehold\.it\/(.+)(jpg?)\/fff/) + assert @tester.image('300x300', 'jpg', 'fff', '000').match(%r{https:\/\/placehold\.it\/(.+)(jpg?)\/fff}) end def test_avatar_font_color_with_wrong_six_char_hex @@ -82,11 +82,10 @@ def test_avatar_font_color_with_wrong_three_char_hex end def test_text_not_present - assert @tester.image('300x300', 'jpg', 'fff', '000').match(/https:\/\/placehold\.it\/[^\\?]+$/) + assert @tester.image('300x300', 'jpg', 'fff', '000').match(%r{https:\/\/placehold\.it\/[^\\?]+$}) end def test_text_present - assert @tester.image('300x300', 'jpg', 'fff', '000', 'hello').match(/https:\/\/placehold\.it\/(.+)\?text=hello/) + assert @tester.image('300x300', 'jpg', 'fff', '000', 'hello').match(%r{https:\/\/placehold\.it\/(.+)\?text=hello}) end - end diff --git a/test/test_pt_locale.rb b/test/test_pt_locale.rb index df2f1a5bbc..1c71105015 100644 --- a/test/test_pt_locale.rb +++ b/test/test_pt_locale.rb @@ -2,7 +2,7 @@ class TestPtLocale < Test::Unit::TestCase def setup - Faker::Config.locale = "pt" + Faker::Config.locale = 'pt' end def teardown diff --git a/test/test_seeding.rb b/test/test_seeding.rb index e6c4faafb1..20353e56cf 100644 --- a/test/test_seeding.rb +++ b/test/test_seeding.rb @@ -1,22 +1,20 @@ require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestSeeding < Test::Unit::TestCase - def setup - end + def setup; end def test_deterministic Faker::Config.random = Random.new(5) - first_random = Faker::Number.number(100000) + first_random = Faker::Number.number(100_000) Faker::Config.random = Random.new(5) - second_random = Faker::Number.number(100000) + second_random = Faker::Number.number(100_000) Faker::Config.random = Random.new Faker::Config.random = nil - third_random = Faker::Number.number(100000) + third_random = Faker::Number.number(100_000) assert first_random == second_random # Tiny chance this will fail randomly if the unseeded Random just so # happen generates the same number as Random.new(5) assert first_random != third_random end - -end \ No newline at end of file +end diff --git a/test/test_sv_locale.rb b/test/test_sv_locale.rb index 3076ee36d9..baed639d2f 100644 --- a/test/test_sv_locale.rb +++ b/test/test_sv_locale.rb @@ -22,7 +22,7 @@ def test_sv_phone_number assert Faker::PhoneNumber.phone_number.match(/^\d{4}[\s\-]?\d{4,6}$/) end - def test_sv_post_code + def test_sv_post_code assert Faker::Address.postcode.match(/^[\d]{5}$/) end end diff --git a/test/test_uk_locale.rb b/test/test_uk_locale.rb index 46744cd88d..1104554719 100644 --- a/test/test_uk_locale.rb +++ b/test/test_uk_locale.rb @@ -3,7 +3,7 @@ class TestUkLocale < Test::Unit::TestCase def setup @previous_locale = Faker::Config.locale - Faker::Config.locale = "uk" + Faker::Config.locale = 'uk' end def teardown @@ -27,15 +27,15 @@ def test_uk_street_prefix_returns_true_value end def test_uk_city_prefix_absent - assert_equal("", Faker::Address.city_prefix) + assert_equal('', Faker::Address.city_prefix) end def test_uk_city_suffix_absent - assert_equal("", Faker::Address.city_suffix) + assert_equal('', Faker::Address.city_suffix) end def test_uk_states_do_not_have_abbreviations - assert_equal("", Faker::Address.state_abbr) + assert_equal('', Faker::Address.state_abbr) end def test_uk_company_prefix_returns_true_value diff --git a/test/test_zh_cn_locale.rb b/test/test_zh_cn_locale.rb index 4f8dff3964..49a77e9a28 100644 --- a/test/test_zh_cn_locale.rb +++ b/test/test_zh_cn_locale.rb @@ -13,5 +13,4 @@ def test_validity_of_phone_method_output cn_cell_phone_validation_regex = /^1(3[0-9]|4[57]|5[0-35-9]|7[0-35-8]|8[0-9])\d{8}$/ assert_match(cn_cell_phone_validation_regex, Faker::PhoneNumber.cell_phone) end - end diff --git a/test/test_zh_locale.rb b/test/test_zh_locale.rb index 65e08b9bf6..bfaa21a464 100644 --- a/test/test_zh_locale.rb +++ b/test/test_zh_locale.rb @@ -24,4 +24,4 @@ def test_ch_methods assert Faker::University.suffix.is_a? String assert Faker::University.name.is_a? String end -end \ No newline at end of file +end