.d"
].freeze
INTERPOLATION_PATTERN = Regexp.union(DEFAULT_INTERPOLATION_PATTERNS)
deprecate_constant :INTERPOLATION_PATTERN
INTERPOLATION_PATTERNS_CACHE = Hash.new do |hash, patterns|
hash[patterns] = Regexp.union(patterns)
end
private_constant :INTERPOLATION_PATTERNS_CACHE
class << self
# Return String or raises MissingInterpolationArgument exception.
# Missing argument's logic is handled by I18n.config.missing_interpolation_argument_handler.
def interpolate(string, values)
raise ReservedInterpolationKey.new($1.to_sym, string) if string =~ I18n.reserved_keys_pattern
raise ArgumentError.new('Interpolation values must be a Hash.') unless values.kind_of?(Hash)
interpolate_hash(string, values)
end
def interpolate_hash(string, values)
pattern = INTERPOLATION_PATTERNS_CACHE[config.interpolation_patterns]
interpolated = false
interpolated_string = string.gsub(pattern) do |match|
interpolated = true
if match == '%%'
'%'
else
key = ($1 || $2 || match.tr("%{}", "")).to_sym
value = if values.key?(key)
values[key]
else
config.missing_interpolation_argument_handler.call(key, values, string)
end
value = value.call(values) if value.respond_to?(:call)
$3 ? sprintf("%#{$3}", value) : value
end
end
interpolated ? interpolated_string : string
end
end
end
i18n-1.14.7/lib/i18n/locale.rb 0000664 0000000 0000000 00000000235 14743300461 0015476 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module I18n
module Locale
autoload :Fallbacks, 'i18n/locale/fallbacks'
autoload :Tag, 'i18n/locale/tag'
end
end
i18n-1.14.7/lib/i18n/locale/ 0000775 0000000 0000000 00000000000 14743300461 0015151 5 ustar 00root root 0000000 0000000 i18n-1.14.7/lib/i18n/locale/fallbacks.rb 0000664 0000000 0000000 00000006665 14743300461 0017435 0 ustar 00root root 0000000 0000000 # Locale Fallbacks
#
# Extends the I18n module to hold a fallbacks instance which is set to an
# instance of I18n::Locale::Fallbacks by default but can be swapped with a
# different implementation.
#
# Locale fallbacks will compute a number of fallback locales for a given locale.
# For example:
#
#
# I18n.fallbacks[:"es-MX"] # => [:"es-MX", :es, :en]
#
# Locale fallbacks always fall back to
#
# * all parent locales of a given locale (e.g. :es for :"es-MX") first,
# * the current default locales and all of their parents second
#
# The default locales are set to [] by default but can be set to something else.
#
# One can additionally add any number of additional fallback locales manually.
# These will be added before the default locales to the fallback chain. For
# example:
#
# # using a custom locale as default fallback locale
#
# I18n.fallbacks = I18n::Locale::Fallbacks.new(:"en-GB", :"de-AT" => :de, :"de-CH" => :de)
# I18n.fallbacks[:"de-AT"] # => [:"de-AT", :de, :"en-GB", :en]
# I18n.fallbacks[:"de-CH"] # => [:"de-CH", :de, :"en-GB", :en]
#
# # mapping fallbacks to an existing instance
#
# # people speaking Catalan also speak Spanish as spoken in Spain
# fallbacks = I18n.fallbacks
# fallbacks.map(:ca => :"es-ES")
# fallbacks[:ca] # => [:ca, :"es-ES", :es, :"en-US", :en]
#
# # people speaking Arabian as spoken in Palestine also speak Hebrew as spoken in Israel
# fallbacks.map(:"ar-PS" => :"he-IL")
# fallbacks[:"ar-PS"] # => [:"ar-PS", :ar, :"he-IL", :he, :"en-US", :en]
# fallbacks[:"ar-EG"] # => [:"ar-EG", :ar, :"en-US", :en]
#
# # people speaking Sami as spoken in Finland also speak Swedish and Finnish as spoken in Finland
# fallbacks.map(:sms => [:"se-FI", :"fi-FI"])
# fallbacks[:sms] # => [:sms, :"se-FI", :se, :"fi-FI", :fi, :"en-US", :en]
module I18n
module Locale
class Fallbacks < Hash
def initialize(*mappings)
@map = {}
map(mappings.pop) if mappings.last.is_a?(Hash)
self.defaults = mappings.empty? ? [] : mappings
end
def defaults=(defaults)
@defaults = defaults.flat_map { |default| compute(default, false) }
end
attr_reader :defaults
def [](locale)
raise InvalidLocale.new(locale) if locale.nil?
raise Disabled.new('fallback#[]') if locale == false
locale = locale.to_sym
super || store(locale, compute(locale))
end
def map(*args, &block)
if args.count == 1 && !block_given?
mappings = args.first
mappings.each do |from, to|
from, to = from.to_sym, Array(to)
to.each do |_to|
@map[from] ||= []
@map[from] << _to.to_sym
end
end
else
@map.map(*args, &block)
end
end
def empty?
@map.empty? && @defaults.empty?
end
def inspect
"#<#{self.class.name} @map=#{@map.inspect} @defaults=#{@defaults.inspect}>"
end
protected
def compute(tags, include_defaults = true, exclude = [])
result = []
Array(tags).each do |tag|
tags = I18n::Locale::Tag.tag(tag).self_and_parents.map! { |t| t.to_sym } - exclude
result += tags
tags.each { |_tag| result += compute(@map[_tag], false, exclude + result) if @map[_tag] }
end
result.push(*defaults) if include_defaults
result.uniq!
result.compact!
result
end
end
end
end
i18n-1.14.7/lib/i18n/locale/tag.rb 0000664 0000000 0000000 00000001452 14743300461 0016253 0 ustar 00root root 0000000 0000000 # encoding: utf-8
module I18n
module Locale
module Tag
autoload :Parents, 'i18n/locale/tag/parents'
autoload :Rfc4646, 'i18n/locale/tag/rfc4646'
autoload :Simple, 'i18n/locale/tag/simple'
class << self
# Returns the current locale tag implementation. Defaults to +I18n::Locale::Tag::Simple+.
def implementation
@@implementation ||= Simple
end
# Sets the current locale tag implementation. Use this to set a different locale tag implementation.
def implementation=(implementation)
@@implementation = implementation
end
# Factory method for locale tags. Delegates to the current locale tag implementation.
def tag(tag)
implementation.tag(tag)
end
end
end
end
end
i18n-1.14.7/lib/i18n/locale/tag/ 0000775 0000000 0000000 00000000000 14743300461 0015724 5 ustar 00root root 0000000 0000000 i18n-1.14.7/lib/i18n/locale/tag/parents.rb 0000664 0000000 0000000 00000001013 14743300461 0017720 0 ustar 00root root 0000000 0000000 module I18n
module Locale
module Tag
module Parents
def parent
@parent ||=
begin
segs = to_a
segs.compact!
segs.length > 1 ? self.class.tag(*segs[0..(segs.length - 2)].join('-')) : nil
end
end
def self_and_parents
@self_and_parents ||= [self].concat parents
end
def parents
@parents ||= parent ? [parent].concat(parent.parents) : []
end
end
end
end
end
i18n-1.14.7/lib/i18n/locale/tag/rfc4646.rb 0000664 0000000 0000000 00000004663 14743300461 0017360 0 ustar 00root root 0000000 0000000 # RFC 4646/47 compliant Locale tag implementation that parses locale tags to
# subtags such as language, script, region, variant etc.
#
# For more information see by http://en.wikipedia.org/wiki/IETF_language_tag
#
# Rfc4646::Parser does not implement grandfathered tags.
module I18n
module Locale
module Tag
RFC4646_SUBTAGS = [ :language, :script, :region, :variant, :extension, :privateuse, :grandfathered ]
RFC4646_FORMATS = { :language => :downcase, :script => :capitalize, :region => :upcase, :variant => :downcase }
class Rfc4646 < Struct.new(*RFC4646_SUBTAGS)
class << self
# Parses the given tag and returns a Tag instance if it is valid.
# Returns false if the given tag is not valid according to RFC 4646.
def tag(tag)
matches = parser.match(tag)
new(*matches) if matches
end
def parser
@@parser ||= Rfc4646::Parser
end
def parser=(parser)
@@parser = parser
end
end
include Parents
RFC4646_FORMATS.each do |name, format|
define_method(name) { self[name].send(format) unless self[name].nil? }
end
def to_sym
to_s.to_sym
end
def to_s
@tag ||= to_a.compact.join("-")
end
def to_a
members.collect { |attr| self.send(attr) }
end
module Parser
PATTERN = %r{\A(?:
([a-z]{2,3}(?:(?:-[a-z]{3}){0,3})?|[a-z]{4}|[a-z]{5,8}) # language
(?:-([a-z]{4}))? # script
(?:-([a-z]{2}|\d{3}))? # region
(?:-([0-9a-z]{5,8}|\d[0-9a-z]{3}))* # variant
(?:-([0-9a-wyz](?:-[0-9a-z]{2,8})+))* # extension
(?:-(x(?:-[0-9a-z]{1,8})+))?| # privateuse subtag
(x(?:-[0-9a-z]{1,8})+)| # privateuse tag
/* ([a-z]{1,3}(?:-[0-9a-z]{2,8}){1,2}) */ # grandfathered
)\z}xi
class << self
def match(tag)
c = PATTERN.match(tag.to_s).captures
c[0..4] << (c[5].nil? ? c[6] : c[5]) << c[7] # TODO c[7] is grandfathered, throw a NotImplemented exception here?
rescue
false
end
end
end
end
end
end
end
i18n-1.14.7/lib/i18n/locale/tag/simple.rb 0000664 0000000 0000000 00000001221 14743300461 0017536 0 ustar 00root root 0000000 0000000 # Simple Locale tag implementation that computes subtags by simply splitting
# the locale tag at '-' occurrences.
module I18n
module Locale
module Tag
class Simple
class << self
def tag(tag)
new(tag)
end
end
include Parents
attr_reader :tag
def initialize(*tag)
@tag = tag.join('-').to_sym
end
def subtags
@subtags = tag.to_s.split('-').map!(&:to_s)
end
def to_sym
tag
end
def to_s
tag.to_s
end
def to_a
subtags
end
end
end
end
end
i18n-1.14.7/lib/i18n/middleware.rb 0000664 0000000 0000000 00000000354 14743300461 0016356 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module I18n
class Middleware
def initialize(app)
@app = app
end
def call(env)
@app.call(env)
ensure
Thread.current[:i18n_config] = I18n::Config.new
end
end
end
i18n-1.14.7/lib/i18n/tests.rb 0000664 0000000 0000000 00000000737 14743300461 0015410 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module I18n
module Tests
autoload :Basics, 'i18n/tests/basics'
autoload :Defaults, 'i18n/tests/defaults'
autoload :Interpolation, 'i18n/tests/interpolation'
autoload :Link, 'i18n/tests/link'
autoload :Localization, 'i18n/tests/localization'
autoload :Lookup, 'i18n/tests/lookup'
autoload :Pluralization, 'i18n/tests/pluralization'
autoload :Procs, 'i18n/tests/procs'
end
end
i18n-1.14.7/lib/i18n/tests/ 0000775 0000000 0000000 00000000000 14743300461 0015054 5 ustar 00root root 0000000 0000000 i18n-1.14.7/lib/i18n/tests/basics.rb 0000664 0000000 0000000 00000004334 14743300461 0016651 0 ustar 00root root 0000000 0000000 module I18n
module Tests
module Basics
def teardown
I18n.available_locales = nil
end
test "available_locales returns the available_locales produced by the backend, by default" do
I18n.backend.store_translations('de', :foo => 'bar')
I18n.backend.store_translations('en', :foo => 'foo')
assert_equal I18n.available_locales, I18n.backend.available_locales
end
test "available_locales can be set to something else independently from the actual locale data" do
I18n.backend.store_translations('de', :foo => 'bar')
I18n.backend.store_translations('en', :foo => 'foo')
I18n.available_locales = :foo
assert_equal [:foo], I18n.available_locales
I18n.available_locales = [:foo, 'bar']
assert_equal [:foo, :bar], I18n.available_locales
I18n.available_locales = nil
assert_equal I18n.available_locales, I18n.backend.available_locales
end
test "available_locales memoizes when set explicitly" do
I18n.backend.expects(:available_locales).never
I18n.available_locales = [:foo]
I18n.backend.store_translations('de', :bar => 'baz')
I18n.reload!
assert_equal [:foo], I18n.available_locales
end
test "available_locales delegates to the backend when not set explicitly" do
original_available_locales_value = I18n.backend.available_locales
I18n.backend.expects(:available_locales).returns(original_available_locales_value).twice
assert_equal I18n.backend.available_locales, I18n.available_locales
end
test "exists? is implemented by the backend" do
I18n.backend.store_translations(:foo, :bar => 'baz')
assert I18n.exists?(:bar, :foo)
end
test "storing a nil value as a translation removes it from the available locale data" do
I18n.backend.store_translations(:en, :to_be_deleted => 'bar')
assert_equal 'bar', I18n.t(:to_be_deleted, :default => 'baz')
I18n.cache_store.clear if I18n.respond_to?(:cache_store) && I18n.cache_store
I18n.backend.store_translations(:en, :to_be_deleted => nil)
assert_equal 'baz', I18n.t(:to_be_deleted, :default => 'baz')
end
end
end
end
i18n-1.14.7/lib/i18n/tests/defaults.rb 0000664 0000000 0000000 00000004374 14743300461 0017220 0 ustar 00root root 0000000 0000000 # encoding: utf-8
module I18n
module Tests
module Defaults
def setup
super
I18n.backend.store_translations(:en, :foo => { :bar => 'bar', :baz => 'baz' })
end
test "defaults: given nil as a key it returns the given default" do
assert_equal 'default', I18n.t(nil, :default => 'default')
end
test "defaults: given a symbol as a default it translates the symbol" do
assert_equal 'bar', I18n.t(nil, :default => :'foo.bar')
end
test "defaults: given a symbol as a default and a scope it stays inside the scope when looking up the symbol" do
assert_equal 'bar', I18n.t(:missing, :default => :bar, :scope => :foo)
end
test "defaults: given an array as a default it returns the first match" do
assert_equal 'bar', I18n.t(:does_not_exist, :default => [:does_not_exist_2, :'foo.bar'])
end
test "defaults: given an array as a default with false it returns false" do
assert_equal false, I18n.t(:does_not_exist, :default => [false])
end
test "defaults: given false it returns false" do
assert_equal false, I18n.t(:does_not_exist, :default => false)
end
test "defaults: given nil it returns nil" do
assert_nil I18n.t(:does_not_exist, :default => nil)
end
test "defaults: given an array of missing keys it raises a MissingTranslationData exception" do
assert_raises I18n::MissingTranslationData do
I18n.t(:does_not_exist, :default => [:does_not_exist_2, :does_not_exist_3], :raise => true)
end
end
test "defaults: using a custom scope separator" do
# data must have been stored using the custom separator when using the ActiveRecord backend
I18n.backend.store_translations(:en, { :foo => { :bar => 'bar' } }, { :separator => '|' })
assert_equal 'bar', I18n.t(nil, :default => :'foo|bar', :separator => '|')
end
# Addresses issue: #599
test "defaults: only interpolates once when resolving defaults" do
I18n.backend.store_translations(:en, :greeting => 'hey %{name}')
assert_equal 'hey %{dont_interpolate_me}',
I18n.t(:does_not_exist, :name => '%{dont_interpolate_me}', default: [:greeting])
end
end
end
end
i18n-1.14.7/lib/i18n/tests/interpolation.rb 0000664 0000000 0000000 00000021047 14743300461 0020274 0 ustar 00root root 0000000 0000000 # encoding: utf-8
module I18n
module Tests
module Interpolation
# If no interpolation parameter is not given, I18n should not alter the string.
# This behavior is due to three reasons:
#
# * Checking interpolation keys in all strings hits performance, badly;
#
# * This allows us to retrieve untouched values through I18n. For example
# I could have a middleware that returns I18n lookup results in JSON
# to be processed through Javascript. Leaving the keys untouched allows
# the interpolation to happen at the javascript level;
#
# * Security concerns: if I allow users to translate a web site, they can
# insert %{} in messages causing the I18n lookup to fail in every request.
#
test "interpolation: given no values it does not alter the string" do
assert_equal 'Hi %{name}!', interpolate(:default => 'Hi %{name}!')
end
test "interpolation: given values it interpolates them into the string" do
assert_equal 'Hi David!', interpolate(:default => 'Hi %{name}!', :name => 'David')
end
test "interpolation: works with a pipe" do
assert_equal 'Hi david!', interpolate(:default => 'Hi %{name|lowercase}!', :'name|lowercase' => 'david')
end
test "interpolation: given a nil value it still interpolates it into the string" do
assert_equal 'Hi !', interpolate(:default => 'Hi %{name}!', :name => nil)
end
test "interpolation: given a lambda as a value it calls it if the string contains the key" do
assert_equal 'Hi David!', interpolate(:default => 'Hi %{name}!', :name => lambda { |*args| 'David' })
end
test "interpolation: given a lambda as a value it does not call it if the string does not contain the key" do
assert_nothing_raised { interpolate(:default => 'Hi!', :name => lambda { |*args| raise 'fail' }) }
end
test "interpolation: given values but missing a key it raises I18n::MissingInterpolationArgument" do
assert_raises(I18n::MissingInterpolationArgument) do
interpolate(:default => '%{foo}', :bar => 'bar')
end
end
test "interpolation: it does not raise I18n::MissingInterpolationArgument for escaped variables" do
assert_nothing_raised do
assert_equal 'Barr %{foo}', interpolate(:default => '%{bar} %%{foo}', :bar => 'Barr')
end
end
test "interpolation: it does not change the original, stored translation string" do
I18n.backend.store_translations(:en, :interpolate => 'Hi %{name}!')
assert_equal 'Hi David!', interpolate(:interpolate, :name => 'David')
assert_equal 'Hi Yehuda!', interpolate(:interpolate, :name => 'Yehuda')
end
test "interpolation: given an array interpolates each element" do
I18n.backend.store_translations(:en, :array_interpolate => ['Hi', 'Mr. %{name}', 'or sir %{name}'])
assert_equal ['Hi', 'Mr. Bartuz', 'or sir Bartuz'], interpolate(:array_interpolate, :name => 'Bartuz')
end
test "interpolation: given the translation is in utf-8 it still works" do
assert_equal 'Häi David!', interpolate(:default => 'Häi %{name}!', :name => 'David')
end
test "interpolation: given the value is in utf-8 it still works" do
assert_equal 'Hi ゆきひろ!', interpolate(:default => 'Hi %{name}!', :name => 'ゆきひろ')
end
test "interpolation: given the translation and the value are in utf-8 it still works" do
assert_equal 'こんにちは、ゆきひろさん!', interpolate(:default => 'こんにちは、%{name}さん!', :name => 'ゆきひろ')
end
if Object.const_defined?(:Encoding)
test "interpolation: given a euc-jp translation and a utf-8 value it raises Encoding::CompatibilityError" do
assert_raises(Encoding::CompatibilityError) do
interpolate(:default => euc_jp('こんにちは、%{name}さん!'), :name => 'ゆきひろ')
end
end
test "interpolation: given a utf-8 translation and a euc-jp value it raises Encoding::CompatibilityError" do
assert_raises(Encoding::CompatibilityError) do
interpolate(:default => 'こんにちは、%{name}さん!', :name => euc_jp('ゆきひろ'))
end
end
test "interpolation: ASCII strings in the backend should be encoded to UTF8 if interpolation options are in UTF8" do
I18n.backend.store_translations 'en', 'encoding' => ('%{who} let me go'.force_encoding("ASCII"))
result = I18n.t 'encoding', :who => "måmmå miå"
assert_equal Encoding::UTF_8, result.encoding
end
test "interpolation: UTF8 strings in the backend are still returned as UTF8 with ASCII interpolation" do
I18n.backend.store_translations 'en', 'encoding' => 'måmmå miå %{what}'
result = I18n.t 'encoding', :what => 'let me go'.force_encoding("ASCII")
assert_equal Encoding::UTF_8, result.encoding
end
test "interpolation: UTF8 strings in the backend are still returned as UTF8 even with numbers interpolation" do
I18n.backend.store_translations 'en', 'encoding' => '%{count} times: måmmå miå'
result = I18n.t 'encoding', :count => 3
assert_equal Encoding::UTF_8, result.encoding
end
end
test "interpolation: given a translations containing a reserved key it raises I18n::ReservedInterpolationKey" do
assert_raises(I18n::ReservedInterpolationKey) { interpolate(:foo => :bar, :default => '%{exception_handler}') }
assert_raises(I18n::ReservedInterpolationKey) { interpolate(:foo => :bar, :default => '%{default}') }
assert_raises(I18n::ReservedInterpolationKey) { interpolate(:foo => :bar, :default => '%{separator}') }
assert_raises(I18n::ReservedInterpolationKey) { interpolate(:foo => :bar, :default => '%{scope}') }
assert_raises(I18n::ReservedInterpolationKey) { interpolate(:default => '%{scope}') }
I18n.backend.store_translations(:en, :interpolate => 'Hi %{scope}!')
assert_raises(I18n::ReservedInterpolationKey) { interpolate(:interpolate) }
end
test "interpolation: it does not raise I18n::ReservedInterpolationKey for escaped variables" do
assert_nothing_raised do
assert_equal '%{separator}', interpolate(:foo => :bar, :default => '%%{separator}')
end
# Note: The two interpolations below do not remove the escape character (%) because
# I18n should not alter the strings when no interpolation parameters are given,
# see the comment at the top of this file.
assert_nothing_raised do
assert_equal '%%{scope}', interpolate(:default => '%%{scope}')
end
I18n.backend.store_translations(:en, :interpolate => 'Hi %%{scope}!')
assert_nothing_raised do
assert_equal 'Hi %%{scope}!', interpolate(:interpolate)
end
end
test "interpolation: deep interpolation for default string" do
assert_equal 'Hi %{name}!', interpolate(:default => 'Hi %{name}!', :deep_interpolation => true)
end
test "interpolation: deep interpolation for interpolated string" do
assert_equal 'Hi Ann!', interpolate(:default => 'Hi %{name}!', :name => 'Ann', :deep_interpolation => true)
end
test "interpolation: deep interpolation for Hash" do
people = { :people => { :ann => 'Ann is %{ann}', :john => 'John is %{john}' } }
interpolated_people = { :people => { :ann => 'Ann is good', :john => 'John is big' } }
assert_equal interpolated_people, interpolate(:default => people, :ann => 'good', :john => 'big', :deep_interpolation => true)
end
test "interpolation: deep interpolation for Array" do
people = { :people => ['Ann is %{ann}', 'John is %{john}'] }
interpolated_people = { :people => ['Ann is good', 'John is big'] }
assert_equal interpolated_people, interpolate(:default => people, :ann => 'good', :john => 'big', :deep_interpolation => true)
end
protected
def capture(stream)
begin
stream = stream.to_s
eval "$#{stream} = StringIO.new"
yield
result = eval("$#{stream}").string
ensure
eval("$#{stream} = #{stream.upcase}")
end
result
end
def euc_jp(string)
string.encode!(Encoding::EUC_JP)
end
def interpolate(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
key = args.pop
I18n.backend.translate('en', key, options)
end
end
end
end
i18n-1.14.7/lib/i18n/tests/link.rb 0000664 0000000 0000000 00000005112 14743300461 0016335 0 ustar 00root root 0000000 0000000 # encoding: utf-8
module I18n
module Tests
module Link
test "linked lookup: if a key resolves to a symbol it looks up the symbol" do
I18n.backend.store_translations 'en', {
:link => :linked,
:linked => 'linked'
}
assert_equal 'linked', I18n.backend.translate('en', :link)
end
test "linked lookup: if a key resolves to a dot-separated symbol it looks up the symbol" do
I18n.backend.store_translations 'en', {
:link => :"foo.linked",
:foo => { :linked => 'linked' }
}
assert_equal('linked', I18n.backend.translate('en', :link))
end
test "linked lookup: if a dot-separated key resolves to a symbol it looks up the symbol" do
I18n.backend.store_translations 'en', {
:foo => { :link => :linked },
:linked => 'linked'
}
assert_equal('linked', I18n.backend.translate('en', :'foo.link'))
end
test "linked lookup: if a dot-separated key resolves to a dot-separated symbol it looks up the symbol" do
I18n.backend.store_translations 'en', {
:foo => { :link => :"bar.linked" },
:bar => { :linked => 'linked' }
}
assert_equal('linked', I18n.backend.translate('en', :'foo.link'))
end
test "linked lookup: links always refer to the absolute key" do
I18n.backend.store_translations 'en', {
:foo => { :link => :linked, :linked => 'linked in foo' },
:linked => 'linked absolutely'
}
assert_equal 'linked absolutely', I18n.backend.translate('en', :link, :scope => :foo)
end
test "linked lookup: a link can resolve to a namespace in the middle of a dot-separated key" do
I18n.backend.store_translations 'en', {
:activemodel => { :errors => { :messages => { :blank => "can't be blank" } } },
:activerecord => { :errors => { :messages => :"activemodel.errors.messages" } }
}
assert_equal "can't be blank", I18n.t(:"activerecord.errors.messages.blank")
assert_equal "can't be blank", I18n.t(:"activerecord.errors.messages.blank")
end
test "linked lookup: a link can resolve with option :count" do
I18n.backend.store_translations 'en', {
:counter => :counted,
:counted => { :foo => { :one => "one", :other => "other" }, :bar => "bar" }
}
assert_equal "one", I18n.t(:'counter.foo', count: 1)
assert_equal "other", I18n.t(:'counter.foo', count: 2)
assert_equal "bar", I18n.t(:'counter.bar', count: 3)
end
end
end
end
i18n-1.14.7/lib/i18n/tests/localization.rb 0000664 0000000 0000000 00000001113 14743300461 0020065 0 ustar 00root root 0000000 0000000 module I18n
module Tests
module Localization
autoload :Date, 'i18n/tests/localization/date'
autoload :DateTime, 'i18n/tests/localization/date_time'
autoload :Time, 'i18n/tests/localization/time'
autoload :Procs, 'i18n/tests/localization/procs'
def self.included(base)
base.class_eval do
include I18n::Tests::Localization::Date
include I18n::Tests::Localization::DateTime
include I18n::Tests::Localization::Procs
include I18n::Tests::Localization::Time
end
end
end
end
end i18n-1.14.7/lib/i18n/tests/localization/ 0000775 0000000 0000000 00000000000 14743300461 0017544 5 ustar 00root root 0000000 0000000 i18n-1.14.7/lib/i18n/tests/localization/date.rb 0000664 0000000 0000000 00000012375 14743300461 0021016 0 ustar 00root root 0000000 0000000 # encoding: utf-8
module I18n
module Tests
module Localization
module Date
def setup
super
setup_date_translations
@date = ::Date.new(2008, 3, 1)
end
test "localize Date: given the short format it uses it" do
assert_equal '01. Mär', I18n.l(@date, :format => :short, :locale => :de)
end
test "localize Date: given the long format it uses it" do
assert_equal '01. März 2008', I18n.l(@date, :format => :long, :locale => :de)
end
test "localize Date: given the default format it uses it" do
assert_equal '01.03.2008', I18n.l(@date, :format => :default, :locale => :de)
end
test "localize Date: given a day name format it returns the correct day name" do
assert_equal 'Samstag', I18n.l(@date, :format => '%A', :locale => :de)
end
test "localize Date: given a uppercased day name format it returns the correct day name in upcase" do
assert_equal 'samstag'.upcase, I18n.l(@date, :format => '%^A', :locale => :de)
end
test "localize Date: given an abbreviated day name format it returns the correct abbreviated day name" do
assert_equal 'Sa', I18n.l(@date, :format => '%a', :locale => :de)
end
test "localize Date: given an meridian indicator format it returns the correct meridian indicator" do
assert_equal 'AM', I18n.l(@date, :format => '%p', :locale => :de)
assert_equal 'am', I18n.l(@date, :format => '%P', :locale => :de)
end
test "localize Date: given an abbreviated and uppercased day name format it returns the correct abbreviated day name in upcase" do
assert_equal 'sa'.upcase, I18n.l(@date, :format => '%^a', :locale => :de)
end
test "localize Date: given a month name format it returns the correct month name" do
assert_equal 'März', I18n.l(@date, :format => '%B', :locale => :de)
end
test "localize Date: given a uppercased month name format it returns the correct month name in upcase" do
assert_equal 'märz'.upcase, I18n.l(@date, :format => '%^B', :locale => :de)
end
test "localize Date: given an abbreviated month name format it returns the correct abbreviated month name" do
assert_equal 'Mär', I18n.l(@date, :format => '%b', :locale => :de)
end
test "localize Date: given an abbreviated and uppercased month name format it returns the correct abbreviated month name in upcase" do
assert_equal 'mär'.upcase, I18n.l(@date, :format => '%^b', :locale => :de)
end
test "localize Date: given a date format with the month name upcased it returns the correct value" do
assert_equal '1. FEBRUAR 2008', I18n.l(::Date.new(2008, 2, 1), :format => "%-d. %^B %Y", :locale => :de)
end
test "localize Date: given missing translations it returns the correct error message" do
assert_equal 'Translation missing: fr.date.abbr_month_names', I18n.l(@date, :format => '%b', :locale => :fr)
end
test "localize Date: given an unknown format it does not fail" do
assert_nothing_raised { I18n.l(@date, :format => '%x') }
end
test "localize Date: does not modify the options hash" do
options = { :format => '%b', :locale => :de }
assert_equal 'Mär', I18n.l(@date, **options)
assert_equal({ :format => '%b', :locale => :de }, options)
assert_nothing_raised { I18n.l(@date, **options.freeze) }
end
test "localize Date: given nil with default value it returns default" do
assert_equal 'default', I18n.l(nil, :default => 'default')
end
test "localize Date: given nil it raises I18n::ArgumentError" do
assert_raises(I18n::ArgumentError) { I18n.l(nil) }
end
test "localize Date: given a plain Object it raises I18n::ArgumentError" do
assert_raises(I18n::ArgumentError) { I18n.l(Object.new) }
end
test "localize Date: given a format is missing it raises I18n::MissingTranslationData" do
assert_raises(I18n::MissingTranslationData) { I18n.l(@date, :format => :missing) }
end
test "localize Date: it does not alter the format string" do
assert_equal '01. Februar 2009', I18n.l(::Date.parse('2009-02-01'), :format => :long, :locale => :de)
assert_equal '01. Oktober 2009', I18n.l(::Date.parse('2009-10-01'), :format => :long, :locale => :de)
end
protected
def setup_date_translations
I18n.backend.store_translations :de, {
:date => {
:formats => {
:default => "%d.%m.%Y",
:short => "%d. %b",
:long => "%d. %B %Y",
},
:day_names => %w(Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag),
:abbr_day_names => %w(So Mo Di Mi Do Fr Sa),
:month_names => %w(Januar Februar März April Mai Juni Juli August September Oktober November Dezember).unshift(nil),
:abbr_month_names => %w(Jan Feb Mär Apr Mai Jun Jul Aug Sep Okt Nov Dez).unshift(nil)
}
}
end
end
end
end
end
i18n-1.14.7/lib/i18n/tests/localization/date_time.rb 0000664 0000000 0000000 00000010774 14743300461 0022035 0 ustar 00root root 0000000 0000000 # encoding: utf-8
module I18n
module Tests
module Localization
module DateTime
def setup
super
setup_datetime_translations
@datetime = ::DateTime.new(2008, 3, 1, 6)
@other_datetime = ::DateTime.new(2008, 3, 1, 18)
end
test "localize DateTime: given the short format it uses it" do
assert_equal '01. Mär 06:00', I18n.l(@datetime, :format => :short, :locale => :de)
end
test "localize DateTime: given the long format it uses it" do
assert_equal '01. März 2008 06:00', I18n.l(@datetime, :format => :long, :locale => :de)
end
test "localize DateTime: given the default format it uses it" do
assert_equal 'Sa, 01. Mär 2008 06:00:00 +0000', I18n.l(@datetime, :format => :default, :locale => :de)
end
test "localize DateTime: given a day name format it returns the correct day name" do
assert_equal 'Samstag', I18n.l(@datetime, :format => '%A', :locale => :de)
end
test "localize DateTime: given a uppercased day name format it returns the correct day name in upcase" do
assert_equal 'samstag'.upcase, I18n.l(@datetime, :format => '%^A', :locale => :de)
end
test "localize DateTime: given an abbreviated day name format it returns the correct abbreviated day name" do
assert_equal 'Sa', I18n.l(@datetime, :format => '%a', :locale => :de)
end
test "localize DateTime: given an abbreviated and uppercased day name format it returns the correct abbreviated day name in upcase" do
assert_equal 'sa'.upcase, I18n.l(@datetime, :format => '%^a', :locale => :de)
end
test "localize DateTime: given a month name format it returns the correct month name" do
assert_equal 'März', I18n.l(@datetime, :format => '%B', :locale => :de)
end
test "localize DateTime: given a uppercased month name format it returns the correct month name in upcase" do
assert_equal 'märz'.upcase, I18n.l(@datetime, :format => '%^B', :locale => :de)
end
test "localize DateTime: given an abbreviated month name format it returns the correct abbreviated month name" do
assert_equal 'Mär', I18n.l(@datetime, :format => '%b', :locale => :de)
end
test "localize DateTime: given an abbreviated and uppercased month name format it returns the correct abbreviated month name in upcase" do
assert_equal 'mär'.upcase, I18n.l(@datetime, :format => '%^b', :locale => :de)
end
test "localize DateTime: given a date format with the month name upcased it returns the correct value" do
assert_equal '1. FEBRUAR 2008', I18n.l(::DateTime.new(2008, 2, 1, 6), :format => "%-d. %^B %Y", :locale => :de)
end
test "localize DateTime: given missing translations it returns the correct error message" do
assert_equal 'Translation missing: fr.date.abbr_month_names', I18n.l(@datetime, :format => '%b', :locale => :fr)
end
test "localize DateTime: given a meridian indicator format it returns the correct meridian indicator" do
assert_equal 'AM', I18n.l(@datetime, :format => '%p', :locale => :de)
assert_equal 'PM', I18n.l(@other_datetime, :format => '%p', :locale => :de)
end
test "localize DateTime: given a meridian indicator format it returns the correct meridian indicator in downcase" do
assert_equal 'am', I18n.l(@datetime, :format => '%P', :locale => :de)
assert_equal 'pm', I18n.l(@other_datetime, :format => '%P', :locale => :de)
end
test "localize DateTime: given an unknown format it does not fail" do
assert_nothing_raised { I18n.l(@datetime, :format => '%x') }
end
test "localize DateTime: given a format is missing it raises I18n::MissingTranslationData" do
assert_raises(I18n::MissingTranslationData) { I18n.l(@datetime, :format => :missing) }
end
protected
def setup_datetime_translations
# time translations might have been set up in Tests::Api::Localization::Time
I18n.backend.store_translations :de, {
:time => {
:formats => {
:default => "%a, %d. %b %Y %H:%M:%S %z",
:short => "%d. %b %H:%M",
:long => "%d. %B %Y %H:%M"
},
:am => 'am',
:pm => 'pm'
}
}
end
end
end
end
end
i18n-1.14.7/lib/i18n/tests/localization/procs.rb 0000664 0000000 0000000 00000013136 14743300461 0021223 0 ustar 00root root 0000000 0000000 # encoding: utf-8
module I18n
module Tests
module Localization
module Procs
test "localize: using day names from lambdas" do
setup_time_proc_translations
time = ::Time.utc(2008, 3, 1, 6, 0)
assert_match(/Суббота/, I18n.l(time, :format => "%A, %d %B", :locale => :ru))
assert_match(/суббота/, I18n.l(time, :format => "%d %B (%A)", :locale => :ru))
end
test "localize: using month names from lambdas" do
setup_time_proc_translations
time = ::Time.utc(2008, 3, 1, 6, 0)
assert_match(/марта/, I18n.l(time, :format => "%d %B %Y", :locale => :ru))
assert_match(/Март /, I18n.l(time, :format => "%B %Y", :locale => :ru))
end
test "localize: using abbreviated day names from lambdas" do
setup_time_proc_translations
time = ::Time.utc(2008, 3, 1, 6, 0)
assert_match(/марта/, I18n.l(time, :format => "%d %b %Y", :locale => :ru))
assert_match(/март /, I18n.l(time, :format => "%b %Y", :locale => :ru))
end
test "localize Date: given a format that resolves to a Proc it calls the Proc with the object" do
setup_time_proc_translations
date = ::Date.new(2008, 3, 1)
assert_equal '[Sat, 01 Mar 2008, {}]', I18n.l(date, :format => :proc, :locale => :ru)
end
test "localize Date: given a format that resolves to a Proc it calls the Proc with the object and extra options" do
setup_time_proc_translations
date = ::Date.new(2008, 3, 1)
assert_equal %|[Sat, 01 Mar 2008, #{{:foo=>"foo"}}]|, I18n.l(date, :format => :proc, :foo => 'foo', :locale => :ru)
end
test "localize DateTime: given a format that resolves to a Proc it calls the Proc with the object" do
setup_time_proc_translations
datetime = ::DateTime.new(2008, 3, 1, 6)
assert_equal '[Sat, 01 Mar 2008 06:00:00 +00:00, {}]', I18n.l(datetime, :format => :proc, :locale => :ru)
end
test "localize DateTime: given a format that resolves to a Proc it calls the Proc with the object and extra options" do
setup_time_proc_translations
datetime = ::DateTime.new(2008, 3, 1, 6)
assert_equal %|[Sat, 01 Mar 2008 06:00:00 +00:00, #{{:foo=>"foo"}}]|, I18n.l(datetime, :format => :proc, :foo => 'foo', :locale => :ru)
end
test "localize Time: given a format that resolves to a Proc it calls the Proc with the object" do
setup_time_proc_translations
time = ::Time.utc(2008, 3, 1, 6, 0)
assert_equal I18n::Tests::Localization::Procs.inspect_args([time], {}), I18n.l(time, :format => :proc, :locale => :ru)
end
test "localize Time: given a format that resolves to a Proc it calls the Proc with the object and extra options" do
setup_time_proc_translations
time = ::Time.utc(2008, 3, 1, 6, 0)
options = { :foo => 'foo' }
assert_equal I18n::Tests::Localization::Procs.inspect_args([time], options), I18n.l(time, **options.merge(:format => :proc, :locale => :ru))
end
protected
def self.inspect_args(args, kwargs)
args << kwargs
args = args.map do |arg|
case arg
when ::Time, ::DateTime
arg.strftime('%a, %d %b %Y %H:%M:%S %Z').sub('+0000', '+00:00')
when ::Date
arg.strftime('%a, %d %b %Y')
when Hash
arg.delete(:fallback_in_progress)
arg.delete(:fallback_original_locale)
arg.inspect
else
arg.inspect
end
end
"[#{args.join(', ')}]"
end
def setup_time_proc_translations
I18n.backend.store_translations :ru, {
:time => {
:formats => {
:proc => lambda { |*args, **kwargs| I18n::Tests::Localization::Procs.inspect_args(args, kwargs) }
}
},
:date => {
:formats => {
:proc => lambda { |*args, **kwargs| I18n::Tests::Localization::Procs.inspect_args(args, kwargs) }
},
:'day_names' => lambda { |key, options|
(options[:format] =~ /^%A/) ?
%w(Воскресенье Понедельник Вторник Среда Четверг Пятница Суббота) :
%w(воскресенье понедельник вторник среда четверг пятница суббота)
},
:'month_names' => lambda { |key, options|
(options[:format] =~ /(%d|%e)(\s*)?(%B)/) ?
%w(января февраля марта апреля мая июня июля августа сентября октября ноября декабря).unshift(nil) :
%w(Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь).unshift(nil)
},
:'abbr_month_names' => lambda { |key, options|
(options[:format] =~ /(%d|%e)(\s*)(%b)/) ?
%w(янв. февр. марта апр. мая июня июля авг. сент. окт. нояб. дек.).unshift(nil) :
%w(янв. февр. март апр. май июнь июль авг. сент. окт. нояб. дек.).unshift(nil)
},
}
}
end
end
end
end
end
i18n-1.14.7/lib/i18n/tests/localization/time.rb 0000664 0000000 0000000 00000010544 14743300461 0021033 0 ustar 00root root 0000000 0000000 # encoding: utf-8
module I18n
module Tests
module Localization
module Time
def setup
super
setup_time_translations
@time = ::Time.utc(2008, 3, 1, 6, 0)
@other_time = ::Time.utc(2008, 3, 1, 18, 0)
end
test "localize Time: given the short format it uses it" do
assert_equal '01. Mär 06:00', I18n.l(@time, :format => :short, :locale => :de)
end
test "localize Time: given the long format it uses it" do
assert_equal '01. März 2008 06:00', I18n.l(@time, :format => :long, :locale => :de)
end
# TODO Seems to break on Windows because ENV['TZ'] is ignored. What's a better way to do this?
# def test_localize_given_the_default_format_it_uses_it
# assert_equal 'Sa, 01. Mar 2008 06:00:00 +0000', I18n.l(@time, :format => :default, :locale => :de)
# end
test "localize Time: given a day name format it returns the correct day name" do
assert_equal 'Samstag', I18n.l(@time, :format => '%A', :locale => :de)
end
test "localize Time: given a uppercased day name format it returns the correct day name in upcase" do
assert_equal 'samstag'.upcase, I18n.l(@time, :format => '%^A', :locale => :de)
end
test "localize Time: given an abbreviated day name format it returns the correct abbreviated day name" do
assert_equal 'Sa', I18n.l(@time, :format => '%a', :locale => :de)
end
test "localize Time: given an abbreviated and uppercased day name format it returns the correct abbreviated day name in upcase" do
assert_equal 'sa'.upcase, I18n.l(@time, :format => '%^a', :locale => :de)
end
test "localize Time: given a month name format it returns the correct month name" do
assert_equal 'März', I18n.l(@time, :format => '%B', :locale => :de)
end
test "localize Time: given a uppercased month name format it returns the correct month name in upcase" do
assert_equal 'märz'.upcase, I18n.l(@time, :format => '%^B', :locale => :de)
end
test "localize Time: given an abbreviated month name format it returns the correct abbreviated month name" do
assert_equal 'Mär', I18n.l(@time, :format => '%b', :locale => :de)
end
test "localize Time: given an abbreviated and uppercased month name format it returns the correct abbreviated month name in upcase" do
assert_equal 'mär'.upcase, I18n.l(@time, :format => '%^b', :locale => :de)
end
test "localize Time: given a date format with the month name upcased it returns the correct value" do
assert_equal '1. FEBRUAR 2008', I18n.l(::Time.utc(2008, 2, 1, 6, 0), :format => "%-d. %^B %Y", :locale => :de)
end
test "localize Time: given missing translations it returns the correct error message" do
assert_equal 'Translation missing: fr.date.abbr_month_names', I18n.l(@time, :format => '%b', :locale => :fr)
end
test "localize Time: given a meridian indicator format it returns the correct meridian indicator" do
assert_equal 'AM', I18n.l(@time, :format => '%p', :locale => :de)
assert_equal 'PM', I18n.l(@other_time, :format => '%p', :locale => :de)
end
test "localize Time: given a meridian indicator format it returns the correct meridian indicator in upcase" do
assert_equal 'am', I18n.l(@time, :format => '%P', :locale => :de)
assert_equal 'pm', I18n.l(@other_time, :format => '%P', :locale => :de)
end
test "localize Time: given an unknown format it does not fail" do
assert_nothing_raised { I18n.l(@time, :format => '%x') }
end
test "localize Time: given a format is missing it raises I18n::MissingTranslationData" do
assert_raises(I18n::MissingTranslationData) { I18n.l(@time, :format => :missing) }
end
protected
def setup_time_translations
I18n.backend.store_translations :de, {
:time => {
:formats => {
:default => "%a, %d. %b %Y %H:%M:%S %z",
:short => "%d. %b %H:%M",
:long => "%d. %B %Y %H:%M",
},
:am => 'am',
:pm => 'pm'
}
}
end
end
end
end
end
i18n-1.14.7/lib/i18n/tests/lookup.rb 0000664 0000000 0000000 00000006110 14743300461 0016710 0 ustar 00root root 0000000 0000000 # encoding: utf-8
module I18n
module Tests
module Lookup
def setup
super
I18n.backend.store_translations(:en, :foo => { :bar => 'bar', :baz => 'baz' }, :falsy => false, :truthy => true,
:string => "a", :array => %w(a b c), :hash => { "a" => "b" })
end
test "lookup: it returns a string" do
assert_equal("a", I18n.t(:string))
end
test "lookup: it returns hash" do
assert_equal({ :a => "b" }, I18n.t(:hash))
end
test "lookup: it returns an array" do
assert_equal(%w(a b c), I18n.t(:array))
end
test "lookup: it returns a native true" do
assert I18n.t(:truthy) === true
end
test "lookup: it returns a native false" do
assert I18n.t(:falsy) === false
end
test "lookup: given a missing key, no default and no raise option it returns an error message" do
assert_equal "Translation missing: en.missing", I18n.t(:missing)
end
test "lookup: given a missing key, no default and the raise option it raises MissingTranslationData" do
assert_raises(I18n::MissingTranslationData) { I18n.t(:missing, :raise => true) }
end
test "lookup: does not raise an exception if no translation data is present for the given locale" do
assert_nothing_raised { I18n.t(:foo, :locale => :xx) }
end
test "lookup: does not modify the options hash" do
options = {}
assert_equal "a", I18n.t(:string, **options)
assert_equal({}, options)
assert_nothing_raised { I18n.t(:string, **options.freeze) }
end
test "lookup: given an array of keys it translates all of them" do
assert_equal %w(bar baz), I18n.t([:bar, :baz], :scope => [:foo])
end
test "lookup: using a custom scope separator" do
# data must have been stored using the custom separator when using the ActiveRecord backend
I18n.backend.store_translations(:en, { :foo => { :bar => 'bar' } }, { :separator => '|' })
assert_equal 'bar', I18n.t('foo|bar', :separator => '|')
end
# In fact it probably *should* fail but Rails currently relies on using the default locale instead.
# So we'll stick to this for now until we get it fixed in Rails.
test "lookup: given nil as a locale it does not raise but use the default locale" do
# assert_raises(I18n::InvalidLocale) { I18n.t(:bar, :locale => nil) }
assert_nothing_raised { I18n.t(:bar, :locale => nil) }
end
test "lookup: a resulting String is not frozen" do
assert !I18n.t(:string).frozen?
end
test "lookup: a resulting Array is not frozen" do
assert !I18n.t(:array).frozen?
end
test "lookup: a resulting Hash is not frozen" do
assert !I18n.t(:hash).frozen?
end
# Addresses issue: #599
test "lookup: only interpolates once when resolving symbols" do
I18n.backend.store_translations(:en, foo: :bar, bar: '%{value}')
assert_equal '%{dont_interpolate_me}', I18n.t(:foo, value: '%{dont_interpolate_me}')
end
end
end
end
i18n-1.14.7/lib/i18n/tests/pluralization.rb 0000664 0000000 0000000 00000002521 14743300461 0020276 0 ustar 00root root 0000000 0000000 # encoding: utf-8
module I18n
module Tests
module Pluralization
test "pluralization: given 0 it returns the :zero translation if it is defined" do
assert_equal 'zero', I18n.t(:default => { :zero => 'zero' }, :count => 0)
end
test "pluralization: given 0 it returns the :other translation if :zero is not defined" do
assert_equal 'bars', I18n.t(:default => { :other => 'bars' }, :count => 0)
end
test "pluralization: given 1 it returns the singular translation" do
assert_equal 'bar', I18n.t(:default => { :one => 'bar' }, :count => 1)
end
test "pluralization: given 2 it returns the :other translation" do
assert_equal 'bars', I18n.t(:default => { :other => 'bars' }, :count => 2)
end
test "pluralization: given 3 it returns the :other translation" do
assert_equal 'bars', I18n.t(:default => { :other => 'bars' }, :count => 3)
end
test "pluralization: given nil it returns the whole entry" do
assert_equal({ :one => 'bar' }, I18n.t(:default => { :one => 'bar' }, :count => nil))
end
test "pluralization: given incomplete pluralization data it raises I18n::InvalidPluralizationData" do
assert_raises(I18n::InvalidPluralizationData) { I18n.t(:default => { :one => 'bar' }, :count => 2) }
end
end
end
end
i18n-1.14.7/lib/i18n/tests/procs.rb 0000664 0000000 0000000 00000006755 14743300461 0016544 0 ustar 00root root 0000000 0000000 # encoding: utf-8
module I18n
module Tests
module Procs
test "lookup: given a translation is a proc it calls the proc with the key and interpolation values" do
I18n.backend.store_translations(:en, :a_lambda => lambda { |*args| I18n::Tests::Procs.filter_args(*args) })
assert_equal %|[:a_lambda, #{{:foo=>"foo"}}]|, I18n.t(:a_lambda, :foo => 'foo')
end
test "lookup: given a translation is a proc it passes the interpolation values as keyword arguments" do
I18n.backend.store_translations(:en, :a_lambda => lambda { |key, foo:, **| I18n::Tests::Procs.filter_args(key, foo: foo) })
assert_equal %|[:a_lambda, #{{:foo=>"foo"}}]|, I18n.t(:a_lambda, :foo => 'foo')
end
test "defaults: given a default is a Proc it calls it with the key and interpolation values" do
proc = lambda { |*args| I18n::Tests::Procs.filter_args(*args) }
assert_equal %|[nil, #{{:foo=>"foo"}}]|, I18n.t(nil, :default => proc, :foo => 'foo')
end
test "defaults: given a default is a key that resolves to a Proc it calls it with the key and interpolation values" do
the_lambda = lambda { |*args| I18n::Tests::Procs.filter_args(*args) }
I18n.backend.store_translations(:en, :a_lambda => the_lambda)
assert_equal %|[:a_lambda, #{{:foo=>"foo"}}]|, I18n.t(nil, :default => :a_lambda, :foo => 'foo')
assert_equal %|[:a_lambda, #{{:foo=>"foo"}}]|, I18n.t(nil, :default => [nil, :a_lambda], :foo => 'foo')
end
test "interpolation: given an interpolation value is a lambda it calls it with key and values before interpolating it" do
proc = lambda { |*args| I18n::Tests::Procs.filter_args(*args) }
if RUBY_VERSION < "3.4"
assert_match %r(\[\{:foo=>#\}\]), I18n.t(nil, :default => '%{foo}', :foo => proc)
else
assert_match %r(\[\{foo: #\}\]), I18n.t(nil, :default => '%{foo}', :foo => proc)
end
end
test "interpolation: given a key resolves to a Proc that returns a string then interpolation still works" do
proc = lambda { |*args| "%{foo}: " + I18n::Tests::Procs.filter_args(*args) }
assert_equal %|foo: [nil, #{{:foo=>"foo"}}]|, I18n.t(nil, :default => proc, :foo => 'foo')
end
test "pluralization: given a key resolves to a Proc that returns valid data then pluralization still works" do
proc = lambda { |*args| { :zero => 'zero', :one => 'one', :other => 'other' } }
assert_equal 'zero', I18n.t(:default => proc, :count => 0)
assert_equal 'one', I18n.t(:default => proc, :count => 1)
assert_equal 'other', I18n.t(:default => proc, :count => 2)
end
test "lookup: given the option :resolve => false was passed it does not resolve proc translations" do
I18n.backend.store_translations(:en, :a_lambda => lambda { |*args| I18n::Tests::Procs.filter_args(*args) })
assert_equal Proc, I18n.t(:a_lambda, :resolve => false).class
end
test "lookup: given the option :resolve => false was passed it does not resolve proc default" do
assert_equal Proc, I18n.t(nil, :default => lambda { |*args| I18n::Tests::Procs.filter_args(*args) }, :resolve => false).class
end
def self.filter_args(*args)
args.map do |arg|
if arg.is_a?(Hash)
arg.delete(:fallback_in_progress)
arg.delete(:fallback_original_locale)
arg.delete(:skip_interpolation)
end
arg
end.inspect
end
end
end
end
i18n-1.14.7/lib/i18n/utils.rb 0000664 0000000 0000000 00000002467 14743300461 0015410 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module I18n
module Utils
class << self
if Hash.method_defined?(:except)
def except(hash, *keys)
hash.except(*keys)
end
else
def except(hash, *keys)
hash = hash.dup
keys.each { |k| hash.delete(k) }
hash
end
end
def deep_merge(hash, other_hash, &block)
deep_merge!(hash.dup, other_hash, &block)
end
def deep_merge!(hash, other_hash, &block)
hash.merge!(other_hash) do |key, this_val, other_val|
if this_val.is_a?(Hash) && other_val.is_a?(Hash)
deep_merge(this_val, other_val, &block)
elsif block_given?
yield key, this_val, other_val
else
other_val
end
end
end
def deep_symbolize_keys(hash)
hash.each_with_object({}) do |(key, value), result|
result[key.respond_to?(:to_sym) ? key.to_sym : key] = deep_symbolize_keys_in_object(value)
result
end
end
private
def deep_symbolize_keys_in_object(value)
case value
when Hash
deep_symbolize_keys(value)
when Array
value.map { |e| deep_symbolize_keys_in_object(e) }
else
value
end
end
end
end
end
i18n-1.14.7/lib/i18n/version.rb 0000664 0000000 0000000 00000000104 14743300461 0015717 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module I18n
VERSION = "1.14.7"
end
i18n-1.14.7/test/ 0000775 0000000 0000000 00000000000 14743300461 0013344 5 ustar 00root root 0000000 0000000 i18n-1.14.7/test/api/ 0000775 0000000 0000000 00000000000 14743300461 0014115 5 ustar 00root root 0000000 0000000 i18n-1.14.7/test/api/all_features_test.rb 0000664 0000000 0000000 00000003130 14743300461 0020144 0 ustar 00root root 0000000 0000000 require 'test_helper'
begin
require 'rubygems'
require 'active_support'
rescue LoadError
puts "not testing with Cache enabled because active_support can not be found"
end
class I18nAllFeaturesApiTest < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::Metadata
include I18n::Backend::Cache
include I18n::Backend::Cascade
include I18n::Backend::Fallbacks
include I18n::Backend::Pluralization
include I18n::Backend::Memoize
end
def setup
I18n.backend = I18n::Backend::Chain.new(Backend.new, I18n::Backend::Simple.new)
I18n.cache_store = cache_store
super
end
def teardown
I18n.cache_store.clear if I18n.cache_store
I18n.cache_store = nil
super
end
def cache_store
ActiveSupport::Cache.lookup_store(:memory_store) if cache_available?
end
def cache_available?
defined?(ActiveSupport) && defined?(ActiveSupport::Cache)
end
include I18n::Tests::Basics
include I18n::Tests::Defaults
include I18n::Tests::Interpolation
include I18n::Tests::Link
include I18n::Tests::Lookup
include I18n::Tests::Pluralization
include I18n::Tests::Procs
include I18n::Tests::Localization::Date
include I18n::Tests::Localization::DateTime
include I18n::Tests::Localization::Time
include I18n::Tests::Localization::Procs
test "make sure we use a Chain backend with an all features backend" do
assert_equal I18n::Backend::Chain, I18n.backend.class
assert_equal Backend, I18n.backend.backends.first.class
end
# links: test that keys stored on one backend can link to keys stored on another backend
end
i18n-1.14.7/test/api/cascade_test.rb 0000664 0000000 0000000 00000001320 14743300461 0017060 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nCascadeApiTest < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::Cascade
end
def setup
I18n.backend = Backend.new
super
end
include I18n::Tests::Basics
include I18n::Tests::Defaults
include I18n::Tests::Interpolation
include I18n::Tests::Link
include I18n::Tests::Lookup
include I18n::Tests::Pluralization
include I18n::Tests::Procs
include I18n::Tests::Localization::Date
include I18n::Tests::Localization::DateTime
include I18n::Tests::Localization::Time
include I18n::Tests::Localization::Procs
test "make sure we use a backend with Cascade included" do
assert_equal Backend, I18n.backend.class
end
end
i18n-1.14.7/test/api/chain_test.rb 0000664 0000000 0000000 00000001261 14743300461 0016563 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nApiChainTest < I18n::TestCase
def setup
super
I18n.backend = I18n::Backend::Chain.new(I18n::Backend::Simple.new, I18n.backend)
end
include I18n::Tests::Basics
include I18n::Tests::Defaults
include I18n::Tests::Interpolation
include I18n::Tests::Link
include I18n::Tests::Lookup
include I18n::Tests::Pluralization
include I18n::Tests::Procs
include I18n::Tests::Localization::Date
include I18n::Tests::Localization::DateTime
include I18n::Tests::Localization::Time
include I18n::Tests::Localization::Procs
test "make sure we use the Chain backend" do
assert_equal I18n::Backend::Chain, I18n.backend.class
end
end
i18n-1.14.7/test/api/fallbacks_test.rb 0000664 0000000 0000000 00000001462 14743300461 0017426 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nFallbacksApiTest < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::Fallbacks
end
def setup
I18n.backend = Backend.new
super
end
include I18n::Tests::Basics
include I18n::Tests::Defaults
include I18n::Tests::Interpolation
include I18n::Tests::Link
include I18n::Tests::Lookup
include I18n::Tests::Pluralization
include I18n::Tests::Procs
include I18n::Tests::Localization::Date
include I18n::Tests::Localization::DateTime
include I18n::Tests::Localization::Time
include I18n::Tests::Localization::Procs
test "make sure we use a backend with Fallbacks included" do
assert_equal Backend, I18n.backend.class
end
# links: test that keys stored on one backend can link to keys stored on another backend
end
i18n-1.14.7/test/api/key_value_test.rb 0000664 0000000 0000000 00000001267 14743300461 0017473 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nKeyValueApiTest < I18n::TestCase
include I18n::Tests::Basics
include I18n::Tests::Defaults
include I18n::Tests::Interpolation
include I18n::Tests::Link
include I18n::Tests::Lookup
include I18n::Tests::Pluralization
# include Tests::Api::Procs
include I18n::Tests::Localization::Date
include I18n::Tests::Localization::DateTime
include I18n::Tests::Localization::Time
# include Tests::Api::Localization::Procs
def setup
I18n.backend = I18n::Backend::KeyValue.new({})
super
end
test "make sure we use the KeyValue backend" do
assert_equal I18n::Backend::KeyValue, I18n.backend.class
end
end if I18n::TestCase.key_value?
i18n-1.14.7/test/api/lazy_loadable_test.rb 0000664 0000000 0000000 00000001253 14743300461 0020304 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nLazyLoadableBackendApiTest < I18n::TestCase
def setup
I18n.backend = I18n::Backend::LazyLoadable.new
super
end
include I18n::Tests::Basics
include I18n::Tests::Defaults
include I18n::Tests::Interpolation
include I18n::Tests::Link
include I18n::Tests::Lookup
include I18n::Tests::Pluralization
include I18n::Tests::Procs
include I18n::Tests::Localization::Date
include I18n::Tests::Localization::DateTime
include I18n::Tests::Localization::Time
include I18n::Tests::Localization::Procs
test "make sure we use the LazyLoadable backend" do
assert_equal I18n::Backend::LazyLoadable, I18n.backend.class
end
end
i18n-1.14.7/test/api/memoize_test.rb 0000664 0000000 0000000 00000002766 14743300461 0017161 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nMemoizeBackendWithSimpleApiTest < I18n::TestCase
include I18n::Tests::Basics
include I18n::Tests::Defaults
include I18n::Tests::Interpolation
include I18n::Tests::Link
include I18n::Tests::Lookup
include I18n::Tests::Pluralization
include I18n::Tests::Procs
include I18n::Tests::Localization::Date
include I18n::Tests::Localization::DateTime
include I18n::Tests::Localization::Time
include I18n::Tests::Localization::Procs
class MemoizeBackend < I18n::Backend::Simple
include I18n::Backend::Memoize
end
def setup
I18n.backend = MemoizeBackend.new
super
end
test "make sure we use the MemoizeBackend backend" do
assert_equal MemoizeBackend, I18n.backend.class
end
end
class I18nMemoizeBackendWithKeyValueApiTest < I18n::TestCase
include I18n::Tests::Basics
include I18n::Tests::Defaults
include I18n::Tests::Interpolation
include I18n::Tests::Link
include I18n::Tests::Lookup
include I18n::Tests::Pluralization
include I18n::Tests::Localization::Date
include I18n::Tests::Localization::DateTime
include I18n::Tests::Localization::Time
# include I18n::Tests::Procs
# include I18n::Tests::Localization::Procs
class MemoizeBackend < I18n::Backend::KeyValue
include I18n::Backend::Memoize
end
def setup
I18n.backend = MemoizeBackend.new({})
super
end
test "make sure we use the MemoizeBackend backend" do
assert_equal MemoizeBackend, I18n.backend.class
end
end if I18n::TestCase.key_value?
i18n-1.14.7/test/api/override_test.rb 0000664 0000000 0000000 00000002242 14743300461 0017320 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nOverrideTest < I18n::TestCase
module OverrideInverse
def translate(key, **options)
super(key, **options).reverse
end
alias :t :translate
end
module OverrideSignature
def translate(*args)
args.first + args[1]
end
alias :t :translate
end
def setup
super
@I18n = I18n.dup
@I18n.backend = I18n::Backend::Simple.new
end
test "make sure modules can overwrite I18n methods" do
@I18n.extend OverrideInverse
@I18n.backend.store_translations('en', :foo => 'bar')
assert_equal 'rab', @I18n.translate(:foo, :locale => 'en')
assert_equal 'rab', @I18n.t(:foo, :locale => 'en')
assert_equal 'rab', @I18n.translate!(:foo, :locale => 'en')
assert_equal 'rab', @I18n.t!(:foo, :locale => 'en')
end
test "make sure modules can overwrite I18n signature" do
exception = catch(:exception) do
@I18n.t('Hello', :tokenize => true, :throw => true)
end
assert exception.message
@I18n.extend OverrideSignature
assert_equal 'HelloWelcome message on home page', @I18n.translate('Hello', 'Welcome message on home page', :tokenize => true) # tr8n example
end
end
i18n-1.14.7/test/api/pluralization_test.rb 0000664 0000000 0000000 00000001476 14743300461 0020406 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nPluralizationApiTest < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::Pluralization
end
def setup
I18n.backend = Backend.new
super
end
include I18n::Tests::Basics
include I18n::Tests::Defaults
include I18n::Tests::Interpolation
include I18n::Tests::Link
include I18n::Tests::Lookup
include I18n::Tests::Pluralization
include I18n::Tests::Procs
include I18n::Tests::Localization::Date
include I18n::Tests::Localization::DateTime
include I18n::Tests::Localization::Time
include I18n::Tests::Localization::Procs
test "make sure we use a backend with Pluralization included" do
assert_equal Backend, I18n.backend.class
end
# links: test that keys stored on one backend can link to keys stored on another backend
end
i18n-1.14.7/test/api/simple_test.rb 0000664 0000000 0000000 00000001353 14743300461 0016774 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nSimpleBackendApiTest < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::Pluralization
end
def setup
I18n.backend = I18n::Backend::Simple.new
super
end
include I18n::Tests::Basics
include I18n::Tests::Defaults
include I18n::Tests::Interpolation
include I18n::Tests::Link
include I18n::Tests::Lookup
include I18n::Tests::Pluralization
include I18n::Tests::Procs
include I18n::Tests::Localization::Date
include I18n::Tests::Localization::DateTime
include I18n::Tests::Localization::Time
include I18n::Tests::Localization::Procs
test "make sure we use the Simple backend" do
assert_equal I18n::Backend::Simple, I18n.backend.class
end
end
i18n-1.14.7/test/backend/ 0000775 0000000 0000000 00000000000 14743300461 0014733 5 ustar 00root root 0000000 0000000 i18n-1.14.7/test/backend/cache_file_test.rb 0000664 0000000 0000000 00000004650 14743300461 0020366 0 ustar 00root root 0000000 0000000 require 'test_helper'
require 'fileutils'
require 'tempfile'
module CountWrites
attr_reader :writes
def initialize(*args)
super
@writes = []
end
def store_translations(*args)
super.tap { @writes << args }
end
end
module CacheFileTest
test 'load_translations caches loaded file contents' do
setup_backend!
I18n.load_path = [locales_dir + '/en.yml']
assert_equal 0, @backend.writes.count
@backend.load_translations unless @backend.is_a?(I18n::Backend::Simple)
assert_equal('baz', I18n.t('foo.bar'))
assert_equal 2, @backend.writes.count
@backend.load_translations
assert_equal('baz', I18n.t('foo.bar'))
assert_equal 2, @backend.writes.count
end
test 'setting path_roots normalizes write key' do
setup_backend!
I18n.load_path = [locales_dir + '/en.yml']
@backend.path_roots = [locales_dir]
@backend.load_translations
refute_nil I18n.t("0/en\x01yml", scope: :load_file, locale: :i18n, default: nil)
end
test 'load_translations caches file through updated modification time' do
setup_backend!
Tempfile.open(['test', '.yml']) do |file|
I18n.load_path = [file.path]
File.write(file, { :en => { :foo => { :bar => 'baz' } } }.to_yaml)
assert_equal 0, @backend.writes.count
@backend.load_translations unless @backend.is_a?(I18n::Backend::Simple)
assert_equal('baz', I18n.t('foo.bar'))
assert_equal 2, @backend.writes.count
FileUtils.touch(file, :mtime => Time.now + 1)
@backend.load_translations
assert_equal('baz', I18n.t('foo.bar'))
assert_equal 2, @backend.writes.count
File.write(file, { :en => { :foo => { :bar => 'baa' } } }.to_yaml)
FileUtils.touch(file, :mtime => Time.now + 1)
@backend.load_translations
assert_equal('baa', I18n.t('foo.bar'))
assert_equal 4, @backend.writes.count
end
end
end
class SimpleCacheFileTest < I18n::TestCase
include CacheFileTest
class Backend < I18n::Backend::Simple
include CountWrites
include I18n::Backend::CacheFile
end
def setup_backend!
@backend = I18n.backend = Backend.new
end
end
class KeyValueCacheFileTest < I18n::TestCase
include CacheFileTest
class Backend < I18n::Backend::KeyValue
include CountWrites
include I18n::Backend::CacheFile
def initialize
super({})
end
end
def setup_backend!
@backend = I18n.backend = Backend.new
end
end if I18n::TestCase.key_value?
i18n-1.14.7/test/backend/cache_test.rb 0000664 0000000 0000000 00000007053 14743300461 0017367 0 ustar 00root root 0000000 0000000 require 'test_helper'
require 'openssl'
begin
require 'active_support'
rescue LoadError
$stderr.puts "Skipping cache tests using ActiveSupport"
else
class I18nBackendCacheTest < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::Cache
end
def setup
I18n.backend = Backend.new
super
I18n.cache_store = ActiveSupport::Cache.lookup_store(:memory_store)
I18n.cache_store.clear
I18n.cache_key_digest = nil
end
def teardown
super
I18n.cache_store.clear
I18n.cache_store = nil
end
test "it uses the cache" do
assert I18n.cache_store.is_a?(ActiveSupport::Cache::MemoryStore)
end
test "translate hits the backend and caches the response" do
I18n.backend.expects(:lookup).returns('Foo')
assert_equal 'Foo', I18n.t(:foo)
I18n.backend.expects(:lookup).never
assert_equal 'Foo', I18n.t(:foo)
I18n.backend.expects(:lookup).returns('Bar')
assert_equal 'Bar', I18n.t(:bar)
end
test "translate returns a cached false response" do
I18n.backend.expects(:lookup).never
I18n.cache_store.expects(:read).returns(false)
assert_equal false, I18n.t(:foo)
end
test "still raises MissingTranslationData but also caches it" do
assert_raises(I18n::MissingTranslationData) { I18n.t(:missing, :raise => true) }
assert_raises(I18n::MissingTranslationData) { I18n.t(:missing, :raise => true) }
assert_equal 1, I18n.cache_store.instance_variable_get(:@data).size
# I18n.backend.expects(:lookup).returns(nil)
# assert_raises(I18n::MissingTranslationData) { I18n.t(:missing, :raise => true) }
# I18n.backend.expects(:lookup).never
# assert_raises(I18n::MissingTranslationData) { I18n.t(:missing, :raise => true) }
end
test "MissingTranslationData does not cache custom options" do
I18n.t(:missing, :scope => :foo, :extra => true)
assert_equal 1, I18n.cache_store.instance_variable_get(:@data).size
value = I18n.cache_store.read(I18n.cache_store.instance_variable_get(:@data).keys.first)
assert_equal({ scope: :foo }, value.options)
end
test "uses 'i18n' as a cache key namespace by default" do
assert_equal 0, I18n.backend.send(:cache_key, :en, :foo, {}).index('i18n')
end
test "adds a custom cache key namespace" do
with_cache_namespace('bar') do
assert_equal 0, I18n.backend.send(:cache_key, :en, :foo, {}).index('i18n/bar/')
end
end
test "adds locale and hash of key and hash of options" do
options = { :bar => 1 }
assert_equal "i18n//en/#{:foo.to_s.hash}/#{options.to_s.hash}", I18n.backend.send(:cache_key, :en, :foo, options)
end
test "cache_key uses configured digest method" do
digest = OpenSSL::Digest::SHA256.new
options = { :bar => 1 }
options_hash = options.inspect
with_cache_key_digest(digest) do
assert_equal "i18n//en/#{digest.hexdigest(:foo.to_s)}/#{digest.hexdigest(options_hash)}", I18n.backend.send(:cache_key, :en, :foo, options)
end
end
test "keys should not be equal" do
interpolation_values1 = { :foo => 1, :bar => 2 }
interpolation_values2 = { :foo => 2, :bar => 1 }
key1 = I18n.backend.send(:cache_key, :en, :some_key, interpolation_values1)
key2 = I18n.backend.send(:cache_key, :en, :some_key, interpolation_values2)
assert key1 != key2
end
protected
def with_cache_namespace(namespace)
I18n.cache_namespace = namespace
yield
I18n.cache_namespace = nil
end
def with_cache_key_digest(digest)
I18n.cache_key_digest = digest
yield
I18n.cache_key_digest = nil
end
end
end # AS cache check
i18n-1.14.7/test/backend/cascade_test.rb 0000664 0000000 0000000 00000007053 14743300461 0017707 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nBackendCascadeTest < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::Cascade
end
def setup
super
I18n.backend = Backend.new
store_translations(:en, :foo => 'foo', :bar => { :baz => 'baz' })
@cascade_options = { :step => 1, :offset => 1, :skip_root => false }
end
def lookup(key, options = {})
I18n.t(key, **options.merge(:cascade => @cascade_options))
end
test "still returns an existing translation as usual" do
assert_equal 'foo', lookup(:foo)
assert_equal 'baz', lookup(:'bar.baz')
end
test "falls back by cutting keys off the end of the scope" do
assert_equal 'foo', lookup(:foo, :scope => :'missing')
assert_equal 'foo', lookup(:foo, :scope => :'missing.missing')
assert_equal 'baz', lookup(:baz, :scope => :'bar.missing')
assert_equal 'baz', lookup(:baz, :scope => :'bar.missing.missing')
end
test "raises I18n::MissingTranslationData exception when no translation was found" do
assert_raises(I18n::MissingTranslationData) { lookup(:'foo.missing', :raise => true) }
assert_raises(I18n::MissingTranslationData) { lookup(:'bar.baz.missing', :raise => true) }
assert_raises(I18n::MissingTranslationData) { lookup(:'missing.bar.baz', :raise => true) }
end
test "cascades before evaluating the default" do
assert_equal 'foo', lookup(:foo, :scope => :missing, :default => 'default')
end
test "cascades defaults, too" do
assert_equal 'foo', lookup(nil, :default => [:'missing.missing', :'missing.foo'])
end
test "works with :offset => 2 and a single key" do
@cascade_options[:offset] = 2
lookup(:foo)
end
test "assemble required fallbacks for ActiveRecord validation messages" do
store_translations(:en,
:errors => {
:odd => 'errors.odd',
:reply => { :title => { :blank => 'errors.reply.title.blank' }, :taken => 'errors.reply.taken' },
:topic => { :title => { :format => 'errors.topic.title.format' }, :length => 'errors.topic.length' }
}
)
assert_equal 'errors.reply.title.blank', lookup(:'errors.reply.title.blank', :default => :'errors.topic.title.blank')
assert_equal 'errors.reply.taken', lookup(:'errors.reply.title.taken', :default => :'errors.topic.title.taken')
assert_equal 'errors.topic.title.format', lookup(:'errors.reply.title.format', :default => :'errors.topic.title.format')
assert_equal 'errors.topic.length', lookup(:'errors.reply.title.length', :default => :'errors.topic.title.length')
assert_equal 'errors.odd', lookup(:'errors.reply.title.odd', :default => :'errors.topic.title.odd')
end
test "assemble action view translation helper lookup cascade" do
@cascade_options[:offset] = 2
store_translations(:en,
:menu => { :show => 'menu.show' },
:namespace => {
:menu => { :new => 'namespace.menu.new' },
:controller => {
:menu => { :edit => 'namespace.controller.menu.edit' },
:action => {
:menu => { :destroy => 'namespace.controller.action.menu.destroy' }
}
}
}
)
assert_equal 'menu.show', lookup(:'namespace.controller.action.menu.show')
assert_equal 'namespace.menu.new', lookup(:'namespace.controller.action.menu.new')
assert_equal 'namespace.controller.menu.edit', lookup(:'namespace.controller.action.menu.edit')
assert_equal 'namespace.controller.action.menu.destroy', lookup(:'namespace.controller.action.menu.destroy')
end
end
i18n-1.14.7/test/backend/chain_test.rb 0000664 0000000 0000000 00000013412 14743300461 0017402 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nBackendChainTest < I18n::TestCase
def setup
super
@first = backend(:en => {
:foo => 'Foo', :formats => {
:short => 'short',
:subformats => {:short => 'short'},
},
:plural_1 => { :one => '%{count}' },
:dates => {:a => "A"},
:fallback_bar => nil,
})
@second = backend(:en => {
:bar => 'Bar', :formats => {
:long => 'long',
:subformats => {:long => 'long'},
},
:plural_2 => { :one => 'one' },
:dates => {:a => "B", :b => "B"},
:fallback_bar => 'Bar',
})
@chain = I18n.backend = I18n::Backend::Chain.new(@first, @second)
end
test "looks up translations from the first chained backend" do
assert_equal 'Foo', @first.send(:translations)[:en][:foo]
assert_equal 'Foo', I18n.t(:foo)
end
test "looks up translations from the second chained backend" do
assert_equal 'Bar', @second.send(:translations)[:en][:bar]
assert_equal 'Bar', I18n.t(:bar)
end
test "defaults only apply to lookups on the last backend in the chain" do
assert_equal 'Foo', I18n.t(:foo, :default => 'Bah')
assert_equal 'Bar', I18n.t(:bar, :default => 'Bah')
assert_equal 'Bah', I18n.t(:bah, :default => 'Bah') # default kicks in only here
end
test "default" do
assert_equal 'Fuh', I18n.t(:default => 'Fuh')
assert_equal 'Zero', I18n.t(:default => { :zero => 'Zero' }, :count => 0)
assert_equal({ :zero => 'Zero' }, I18n.t(:default => { :zero => 'Zero' }))
assert_equal 'Foo', I18n.t(:default => :foo)
end
test 'default is returned if translation is missing' do
assert_equal({}, I18n.t(:'i18n.transliterate.rule', :locale => 'en', :default => {}))
end
test "namespace lookup collects results from all backends and merges deep hashes" do
assert_equal({:long=>"long", :subformats=>{:long=>"long", :short=>"short"}, :short=>"short"}, I18n.t(:formats))
end
test "namespace lookup collects results from all backends and lets leftmost backend take priority" do
assert_equal({ :a => "A", :b => "B" }, I18n.t(:dates))
end
test "namespace lookup with only the first backend returning a result" do
assert_equal({ :one => '%{count}' }, I18n.t(:plural_1))
end
test "pluralization still works" do
assert_equal '1', I18n.t(:plural_1, :count => 1)
assert_equal 'one', I18n.t(:plural_2, :count => 1)
end
test "bulk lookup collects results from all backends" do
assert_equal ['Foo', 'Bar'], I18n.t([:foo, :bar])
assert_equal ['Foo', 'Bar', 'Bah'], I18n.t([:foo, :bar, :bah], :default => 'Bah')
assert_equal [{
:long=>"long",
:subformats=>{:long=>"long", :short=>"short"},
:short=>"short"}, {:one=>"one"},
"Bah"], I18n.t([:formats, :plural_2, :bah], :default => 'Bah')
end
test "store_translations options are not dropped while transferring to backend" do
@first.expects(:store_translations).with(:foo, {:bar => :baz}, {:option => 'persists'})
I18n.backend.store_translations :foo, {:bar => :baz}, {:option => 'persists'}
end
test 'store should call initialize on all backends and return true if all initialized' do
@first.send :init_translations
@second.send :init_translations
assert I18n.backend.initialized?
end
test 'store should call initialize on all backends and return false if one not initialized' do
@first.reload!
@second.send :init_translations
assert !I18n.backend.initialized?
end
test 'should reload all backends' do
@first.send :init_translations
@second.send :init_translations
I18n.backend.reload!
assert !@first.initialized?
assert !@second.initialized?
end
test 'should eager load all backends' do
I18n.backend.eager_load!
assert @first.initialized?
assert @second.initialized?
end
test "falls back to other backends for nil values" do
assert_nil @first.send(:translations)[:en][:fallback_bar]
assert_equal 'Bar', @second.send(:translations)[:en][:fallback_bar]
assert_equal 'Bar', I18n.t(:fallback_bar)
end
test 'should be able to get all translations of all backends merged together' do
expected = {
en: {
foo: 'Foo',
bar: 'Bar',
formats: {
short: 'short',
long: 'long',
subformats: { short: 'short', long: 'long' }
},
plural_1: { one: "%{count}" },
plural_2: { one: 'one' },
dates: { a: 'A', b: 'B' },
fallback_bar: 'Bar'
}
}
assert_equal expected, I18n.backend.send(:translations)
end
protected
def backend(translations)
backend = I18n::Backend::Simple.new
translations.each { |locale, data| backend.store_translations(locale, data) }
backend
end
end
class I18nBackendChainWithKeyValueTest < I18n::TestCase
def setup_backend!(subtrees = true)
first = I18n::Backend::KeyValue.new({}, subtrees)
first.store_translations(:en, :plural_1 => { :one => '%{count}' })
second = I18n::Backend::Simple.new
second.store_translations(:en, :plural_2 => { :one => 'one' })
I18n.backend = I18n::Backend::Chain.new(first, second)
end
test "subtrees enabled: looks up pluralization translations from the first chained backend" do
setup_backend!
assert_equal '1', I18n.t(:plural_1, count: 1)
end
test "subtrees disabled: looks up pluralization translations from the first chained backend" do
setup_backend!(false)
assert_equal '1', I18n.t(:plural_1, count: 1)
end
test "subtrees enabled: looks up translations from the second chained backend" do
setup_backend!
assert_equal 'one', I18n.t(:plural_2, count: 1)
end
test "subtrees disabled: looks up translations from the second chained backend" do
setup_backend!(false)
assert_equal 'one', I18n.t(:plural_2, count: 1)
end
end if I18n::TestCase.key_value?
i18n-1.14.7/test/backend/exceptions_test.rb 0000664 0000000 0000000 00000002633 14743300461 0020504 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nBackendExceptionsTest < I18n::TestCase
def setup
super
I18n.backend = I18n::Backend::Simple.new
end
test "throw message: MissingTranslation message from #translate includes the given scope and full key" do
exception = catch(:exception) do
I18n.t(:'baz.missing', :scope => :'foo.bar', :throw => true)
end
assert_equal "Translation missing: en.foo.bar.baz.missing", exception.message
end
test "exceptions: MissingTranslationData message from #translate includes the given scope and full key" do
begin
I18n.t(:'baz.missing', :scope => :'foo.bar', :raise => true)
rescue I18n::MissingTranslationData => exception
end
assert_equal "Translation missing: en.foo.bar.baz.missing", exception.message
end
test "exceptions: MissingTranslationData message from #localize includes the given scope and full key" do
begin
I18n.l(Time.now, :format => :foo)
rescue I18n::MissingTranslationData => exception
end
assert_equal "Translation missing: en.time.formats.foo", exception.message
end
test "exceptions: MissingInterpolationArgument message includes missing key, provided keys and full string" do
exception = I18n::MissingInterpolationArgument.new('key', {:this => 'was given'}, 'string')
assert_equal %|missing interpolation argument "key" in "string" (#{{:this=>"was given"}} given)|, exception.message
end
end
i18n-1.14.7/test/backend/fallbacks_test.rb 0000664 0000000 0000000 00000037771 14743300461 0020260 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nBackendFallbacksTranslateTest < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::Fallbacks
end
def setup
super
I18n.backend = Backend.new
store_translations(:en, :foo => 'Foo in :en', :bar => 'Bar in :en', :buz => 'Buz in :en', :interpolate => 'Interpolate %{value}', :interpolate_count => 'Interpolate %{value} %{count}')
store_translations(:de, :bar => 'Bar in :de', :baz => 'Baz in :de')
store_translations(:'de-DE', :baz => 'Baz in :de-DE')
store_translations(:'pt-BR', :baz => 'Baz in :pt-BR')
end
test "still returns an existing translation as usual" do
assert_equal 'Foo in :en', I18n.t(:foo, :locale => :en)
assert_equal 'Bar in :de', I18n.t(:bar, :locale => :de)
assert_equal 'Baz in :de-DE', I18n.t(:baz, :locale => :'de-DE')
end
test "returns interpolated value if no key provided" do
assert_equal 'Interpolate %{value}', I18n.t(:interpolate)
end
test "returns the :de translation for a missing :'de-DE' translation" do
assert_equal 'Bar in :de', I18n.t(:bar, :locale => :'de-DE')
end
test "keeps the count option when defaulting to a different key" do
assert_equal 'Interpolate 5 10', I18n.t(:non_existent, default: :interpolate_count, count: 10, value: 5)
end
test "returns the :de translation for a missing :'de-DE' when :default is a String" do
assert_equal 'Bar in :de', I18n.t(:bar, :locale => :'de-DE', :default => "Default Bar")
assert_equal "Default Bar", I18n.t(:missing_bar, :locale => :'de-DE', :default => "Default Bar")
end
test "returns the :de translation for a missing :'de-DE' when defaults is a Symbol (which exists in :en)" do
assert_equal "Bar in :de", I18n.t(:bar, :locale => :'de-DE', :default => [:buz])
end
test "returns the :'de-DE' default :baz translation for a missing :'de-DE' (which exists in :de)" do
assert_equal "Baz in :de-DE", I18n.t(:bar, :locale => :'de-DE', :default => [:baz])
end
test "returns the :de translation for a missing :'de-DE' when :default is a Proc" do
assert_equal 'Bar in :de', I18n.t(:bar, :locale => :'de-DE', :default => Proc.new { "Default Bar" })
assert_equal "Default Bar", I18n.t(:missing_bar, :locale => :'de-DE', :default => Proc.new { "Default Bar" })
end
test "returns the :de translation for a missing :'de-DE' when :default is a Hash" do
assert_equal 'Bar in :de', I18n.t(:bar, :locale => :'de-DE', :default => {})
assert_equal({}, I18n.t(:missing_bar, :locale => :'de-DE', :default => {}))
end
test "returns the :de translation for a missing :'de-DE' when :default is nil" do
assert_equal 'Bar in :de', I18n.t(:bar, :locale => :'de-DE', :default => nil)
assert_nil I18n.t(:missing_bar, :locale => :'de-DE', :default => nil)
end
test "returns the Translation missing: message if the default is also missing" do
translation_missing_message = <<~MSG
Translation missing. Options considered were:
- de-DE.missing_bar
- de-DE.missing_baz
MSG
assert_equal translation_missing_message.chomp, I18n.t(:missing_bar, :locale => :'de-DE', :default => [:missing_baz])
end
test "returns the simple Translation missing: message when default is an empty Array" do
assert_equal "Translation missing: de-DE.missing_bar", I18n.t(:missing_bar, :locale => :'de-DE', :default => [])
end
test "returns the :'de-DE' default :baz translation for a missing :'de-DE' when defaults contains Symbol" do
assert_equal 'Baz in :de-DE', I18n.t(:missing_foo, :locale => :'de-DE', :default => [:baz, "Default Bar"])
end
test "returns the defaults translation for a missing :'de-DE' when defaults contains a String or Proc before Symbol" do
assert_equal "Default Bar", I18n.t(:missing_foo, :locale => :'de-DE', :default => [:missing_bar, "Default Bar", :baz])
assert_equal "Default Bar", I18n.t(:missing_foo, :locale => :'de-DE', :default => [:missing_bar, Proc.new { "Default Bar" }, :baz])
end
test "returns the default translation for a missing :'de-DE' and existing :de when default is a Hash" do
assert_equal 'Default 6 Bars', I18n.t(:missing_foo, :locale => :'de-DE', :default => [:missing_bar, {:other => "Default %{count} Bars"}, "Default Bar"], :count => 6)
end
test "returns the default translation for a missing :de translation even when default is a String when fallback is disabled" do
assert_equal 'Default String', I18n.t(:foo, :locale => :de, :default => 'Default String', :fallback => false)
end
test "raises I18n::MissingTranslationData exception when fallback is disabled even when fallback translation exists" do
assert_raises(I18n::MissingTranslationData) { I18n.t(:foo, :locale => :de, :fallback => false, :raise => true) }
end
test "raises I18n::MissingTranslationData exception when no translation was found" do
assert_raises(I18n::MissingTranslationData) { I18n.t(:faa, :locale => :en, :raise => true) }
assert_raises(I18n::MissingTranslationData) { I18n.t(:faa, :locale => :de, :raise => true) }
end
test "should ensure that default is not splitted on new line char" do
assert_equal "Default \n Bar", I18n.t(:missing_bar, :default => "Default \n Bar")
end
test "should not raise error when enforce_available_locales is true, :'pt' is missing and default is a Symbol" do
I18n.enforce_available_locales = true
begin
assert_equal 'Foo', I18n.t(:'model.attrs.foo', :locale => :'pt-BR', :default => [:'attrs.foo', "Foo"])
ensure
I18n.enforce_available_locales = false
end
end
test "returns fallback default given missing pluralization data" do
assert_equal 'default', I18n.t(:missing_bar, count: 1, default: 'default')
assert_equal 'default', I18n.t(:missing_bar, count: 0, default: 'default')
end
test "multi-threaded fallbacks" do
I18n.fallbacks = [:en]
thread = Thread.new do
I18n.fallbacks = [:de]
end
begin
thread.join
assert_equal 'Bar in :en', I18n.t(:bar, :locale => :'pt-BR')
ensure
thread.exit
I18n.fallbacks = I18n::Locale::Fallbacks.new
end
end
end
# See Issue #534
class I18nBackendFallbacksLocalizeTestWithDefaultLocale < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::Fallbacks
end
def setup
super
I18n.backend = Backend.new
I18n.enforce_available_locales = false
I18n.fallbacks = [I18n.default_locale]
store_translations(:en, time: { formats: { fallback: 'en fallback' } })
end
test "falls back to default locale - Issue #534" do
assert_equal 'en fallback', I18n.l(Time.now, format: :fallback, locale: "un-supported")
end
end
# See Issue #536
class I18nBackendFallbacksWithCustomClass < I18n::TestCase
class BackendWithFallbacks < I18n::Backend::Simple
include I18n::Backend::Fallbacks
end
# Quacks like a fallback class
class MyDefaultFallback
def [](key)
[:my_language]
end
end
def setup
super
I18n.backend = BackendWithFallbacks.new
I18n.enforce_available_locales = false
I18n.fallbacks = MyDefaultFallback.new
store_translations(:my_language, foo: 'customer foo')
store_translations(:en, foo: 'english foo')
end
test "can use a default fallback object that doesn't inherit from I18n::Locale::Fallbacks" do
assert_equal 'customer foo', I18n.t(:foo, locale: :en)
assert_equal 'customer foo', I18n.t(:foo, locale: :nothing)
end
end
# See Issue #546
class I18nBackendFallbacksLocalizeTestWithMultipleThreads < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::Fallbacks
end
def setup
super
I18n.backend = Backend.new
I18n.enforce_available_locales = false
I18n.fallbacks = [I18n.default_locale]
store_translations(:en, time: { formats: { fallback: 'en fallback' } })
end
test "falls back to default locale - Issue #546" do
Thread.new { assert_equal 'en fallback', I18n.l(Time.now, format: :fallback, locale: "un-supported") }.join
end
end
# See Issue #590
class I18nBackendFallbacksSymbolResolveRestartsLookupAtOriginalLocale < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::Fallbacks
end
def setup
super
I18n.backend = Backend.new
I18n.enforce_available_locales = false
I18n.fallbacks = [:root]
store_translations(:ak,
'calendars' => {
'gregorian' => {
'months' => {
'format' => {
'abbreviated' => {
1 => 'S-Ɔ'
# Other months omitted for brevity
}
}
}
}
})
store_translations(:root,
'calendars' => {
'gregorian' => {
'months' => {
'format' => {
'abbreviated' => :"calendars.gregorian.months.format.wide",
'wide' => {
1 => 'M01'
# Other months omitted for brevity
}
},
'stand-alone' => {
'abbreviated' => :"calendars.gregorian.months.format.abbreviated"
}
}
}
})
end
test 'falls back to original locale when symbol resolved at fallback locale' do
assert_equal({ 1 => 'S-Ɔ' }, I18n.t('calendars.gregorian.months.stand-alone.abbreviated', locale: :"ak-GH"))
end
end
# See Issue #617
class RegressionTestFor617 < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::Fallbacks
end
def setup
super
I18n.backend = Backend.new
I18n.enforce_available_locales = false
I18n.fallbacks = {:en=>[:en], :"en-US"=>[:"en-US", :en]}
I18n.locale = :'en-US'
store_translations(:"en-US", {})
store_translations(:en, :activerecord=>{:models=>{:product=>{:one=>"Product", :other=>"Products"}, :"product/ticket"=>{:one=>"Ticket", :other=>"Tickets"}}})
end
test 'model scope resolution' do
defaults = [:product, "Ticket"]
options = {:scope=>[:activerecord, :models], :count=>1, :default=> defaults}
assert_equal("Ticket", I18n.t(:"product/ticket", **options))
end
end
class I18nBackendFallbacksLocalizeTest < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::Fallbacks
end
def setup
super
I18n.backend = Backend.new
store_translations(:en, :date => { :formats => { :en => 'en' }, :day_names => %w(Sunday) })
store_translations(:de, :date => { :formats => { :de => 'de' }, :day_names => %w(Sunday) })
end
test "still uses an existing format as usual" do
assert_equal 'en', I18n.l(Date.today, :format => :en, :locale => :en)
end
test "looks up and uses a fallback locale's format for a key missing in the given locale" do
assert_equal 'de', I18n.l(Date.today, :format => :de, :locale => :'de-DE')
end
test "still uses an existing day name translation as usual" do
assert_equal 'Sunday', I18n.l(Date.new(2010, 1, 3), :format => '%A', :locale => :en)
end
test "uses a fallback locale's translation for a key missing in the given locale" do
assert_equal 'Sunday', I18n.l(Date.new(2010, 1, 3), :format => '%A', :locale => :'de-DE')
end
end
class I18nBackendFallbacksWithChainTest < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::Fallbacks
end
class Chain < I18n::Backend::Chain
include I18n::Backend::Fallbacks
end
def setup
super
backend = Backend.new
backend.store_translations(:de, :foo => 'FOO', :nested => { key: "value" })
backend.store_translations(:'pt-BR', :foo => 'Baz in :pt-BR')
I18n.backend = Chain.new(I18n::Backend::Simple.new, backend)
end
test "falls back from de-DE to de when there is no translation for de-DE available" do
assert_equal 'FOO', I18n.t(:foo, :locale => :'de-DE')
end
test "exists? falls back from de-DE to de given a key missing from the given locale" do
assert_equal true, I18n.exists?(:foo, :locale => :'de-DE')
end
test "exists? passes along the scope option" do
assert_equal true, I18n.exists?(:key, :locale => :'de-DE', scope: :nested)
end
test "exists? should return false when fallback disabled given a key missing from the given locale" do
assert_equal false, I18n.exists?(:foo, :locale => :'de-DE', fallback: false)
end
test "falls back from de-DE to de when there is no translation for de-DE available when using arrays, too" do
assert_equal ['FOO', 'FOO'], I18n.t([:foo, :foo], :locale => :'de-DE')
end
test "should not raise error when enforce_available_locales is true, :'pt' is missing and default is a Symbol" do
I18n.enforce_available_locales = true
begin
assert_equal 'Foo', I18n.t(:'model.attrs.foo', :locale => :'pt-BR', :default => [:'attrs.foo', "Foo"])
ensure
I18n.enforce_available_locales = false
end
end
end
class I18nBackendFallbacksExistsTest < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::Fallbacks
end
def setup
super
I18n.backend = Backend.new
store_translations(:en, :foo => 'Foo in :en', :bar => 'Bar in :en')
store_translations(:de, :bar => 'Bar in :de')
store_translations(:'de-DE', :baz => 'Baz in :de-DE')
end
test "exists? given an existing key will return true" do
assert_equal true, I18n.exists?(:foo)
end
test "exists? given a non-existing key will return false" do
assert_equal false, I18n.exists?(:bogus)
end
test "exists? given an existing key and an existing locale will return true" do
assert_equal true, I18n.exists?(:foo, :en)
assert_equal true, I18n.exists?(:bar, :de)
end
test "exists? given a non-existing key and an existing locale will return false" do
assert_equal false, I18n.exists?(:bogus, :en)
assert_equal false, I18n.exists?(:bogus, :de)
end
test "exists? should return true given a key which is missing from the given locale and exists in a fallback locale" do
assert_equal true, I18n.exists?(:bar, :de)
assert_equal true, I18n.exists?(:bar, :'de-DE')
end
test "exists? should return false given a key which is missing from the given locale and all its fallback locales" do
assert_equal false, I18n.exists?(:baz, :de)
assert_equal false, I18n.exists?(:bogus, :'de-DE')
end
test "exists? should return false when fallback is disabled given a key which is missing from the given locale" do
assert_equal true, I18n.exists?(:bar, :'de-DE')
assert_equal false, I18n.exists?(:bar, :'de-DE', fallback: false)
assert_equal false, I18n.exists?(:bar, :'de-DE-XX', fallback: false)
end
end
class I18nBackendOnFallbackHookTest < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::Fallbacks
attr :fallback_collector
private
def on_fallback(*args)
@fallback_collector ||= []
@fallback_collector << args
end
end
def setup
super
I18n.backend = Backend.new
I18n.fallbacks = I18n::Locale::Fallbacks.new(de: :en)
store_translations(:en, :foo => 'Foo in :en', :bar => 'Bar in :en')
store_translations(:de, :bar => 'Bar in :de')
store_translations(:"de-DE", :baz => 'Baz in :"de-DE"')
end
test "on_fallback should be called when fallback happens" do
assert_equal [:"de-DE", :de, :en], I18n.fallbacks[:"de-DE"]
assert_equal 'Baz in :"de-DE"', I18n.t(:baz, locale: :'de-DE')
assert_equal 'Bar in :de', I18n.t(:bar, locale: :'de-DE')
assert_equal 'Foo in :en', I18n.t(:foo, locale: :'de-DE')
assert_equal [:'de-DE', :de, :bar, {}], I18n.backend.fallback_collector[0]
assert_equal [:'de-DE', :en, :foo, {}], I18n.backend.fallback_collector[1]
end
test "on_fallback should not be called when use a String locale" do
assert_equal 'Bar in :de', I18n.t("bar", locale: "de")
assert I18n.backend.fallback_collector.nil?
end
end
i18n-1.14.7/test/backend/interpolation_compiler_test.rb 0000664 0000000 0000000 00000011000 14743300461 0023070 0 ustar 00root root 0000000 0000000 require 'test_helper'
class InterpolationCompilerTest < I18n::TestCase
Compiler = I18n::Backend::InterpolationCompiler::Compiler
def compile_and_interpolate(str, values = {})
Compiler.compile_if_an_interpolation(str).i18n_interpolate(values)
end
def assert_escapes_interpolation_key(expected, malicious_str)
assert_equal(expected, Compiler.send(:escape_key_sym, malicious_str))
end
def test_escape_key_properly_escapes
assert_escapes_interpolation_key ':"\""', '"'
assert_escapes_interpolation_key ':"\\\\"', '\\'
assert_escapes_interpolation_key ':"\\\\\""', '\\"'
assert_escapes_interpolation_key ':"\#{}"', '#{}'
assert_escapes_interpolation_key ':"\\\\\#{}"', '\#{}'
end
def assert_escapes_plain_string(expected, plain_str)
assert_equal expected, Compiler.send(:escape_plain_str, plain_str)
end
def test_escape_plain_string_properly_escapes
assert_escapes_plain_string '\\"', '"'
assert_escapes_plain_string '\'', '\''
assert_escapes_plain_string '\\#', '#'
assert_escapes_plain_string '\\#{}', '#{}'
assert_escapes_plain_string '\\\\\\"','\\"'
end
def test_non_interpolated_strings_or_arrays_dont_get_compiled
['abc', '\\{a}}', '{a}}', []].each do |obj|
Compiler.compile_if_an_interpolation(obj)
assert_equal false, obj.respond_to?(:i18n_interpolate)
end
end
def test_interpolated_string_gets_compiled
assert_equal '-A-', compile_and_interpolate('-%{a}-', :a => 'A')
end
def assert_handles_key(str, key)
assert_equal 'A', compile_and_interpolate(str, key => 'A')
end
def test_compiles_fancy_keys
assert_handles_key('%{\}', :'\\' )
assert_handles_key('%{#}', :'#' )
assert_handles_key('%{#{}', :'#{' )
assert_handles_key('%{#$SAFE}', :'#$SAFE')
assert_handles_key('%{\000}', :'\000' )
assert_handles_key('%{\'}', :'\'' )
assert_handles_key('%{\'\'}', :'\'\'' )
assert_handles_key('%{a.b}', :'a.b' )
assert_handles_key('%{ }', :' ' )
assert_handles_key('%{:}', :':' )
assert_handles_key("%{:''}", :":''" )
assert_handles_key('%{:"}', :':"' )
end
def test_str_containing_only_escaped_interpolation_is_handled_correctly
assert_equal 'abc %{x}', compile_and_interpolate('abc %%{x}')
end
def test_handles_weird_strings
assert_equal '#{} a', compile_and_interpolate('#{} %{a}', :a => 'a')
assert_equal '"#{abc}"', compile_and_interpolate('"#{ab%{a}c}"', :a => '' )
assert_equal 'a}', compile_and_interpolate('%{{a}}', :'{a' => 'a')
assert_equal '"', compile_and_interpolate('"%{a}', :a => '' )
assert_equal 'a%{a}', compile_and_interpolate('%{a}%%{a}', :a => 'a')
assert_equal '%%{a}', compile_and_interpolate('%%%{a}')
assert_equal '\";eval("a")', compile_and_interpolate('\";eval("%{a}")', :a => 'a')
assert_equal '\";eval("a")', compile_and_interpolate('\";eval("a")%{a}', :a => '' )
assert_equal "\na", compile_and_interpolate("\n%{a}", :a => 'a')
end
def test_raises_exception_when_argument_is_missing
assert_raises(I18n::MissingInterpolationArgument) do
compile_and_interpolate('%{first} %{last}', :first => 'first')
end
end
def test_custom_missing_interpolation_argument_handler
old_handler = I18n.config.missing_interpolation_argument_handler
I18n.config.missing_interpolation_argument_handler = lambda do |key, values, string|
"missing key is #{key}, values are #{values.inspect}, given string is '#{string}'"
end
assert_equal %|first missing key is last, values are #{{:first=>"first"}.to_s}, given string is '%{first} %{last}'|,
compile_and_interpolate('%{first} %{last}', :first => 'first')
ensure
I18n.config.missing_interpolation_argument_handler = old_handler
end
end
class I18nBackendInterpolationCompilerTest < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::InterpolationCompiler
end
include I18n::Tests::Interpolation
def setup
I18n.backend = Backend.new
super
end
# pre-compile default strings to make sure we are testing I18n::Backend::InterpolationCompiler
def interpolate(*args)
options = args.last.kind_of?(Hash) ? args.last : {}
if default_str = options[:default]
I18n::Backend::InterpolationCompiler::Compiler.compile_if_an_interpolation(default_str)
end
super
end
end
i18n-1.14.7/test/backend/key_value_test.rb 0000664 0000000 0000000 00000007521 14743300461 0020310 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nBackendKeyValueTest < I18n::TestCase
def setup_backend!(subtree=true)
I18n.backend = I18n::Backend::KeyValue.new({}, subtree)
store_translations(:en, :foo => { :bar => 'bar', :baz => 'baz' })
end
def assert_flattens(expected, nested, escape=true, subtree=true)
assert_equal expected, I18n.backend.flatten_translations("en", nested, escape, subtree)
end
test "hash flattening works" do
setup_backend!
assert_flattens(
{:a=>'a', :b=>{:c=>'c', :d=>'d', :f=>{:x=>'x'}}, :"b.f" => {:x=>"x"}, :"b.c"=>"c", :"b.f.x"=>"x", :"b.d"=>"d"},
{:a=>'a', :b=>{:c=>'c', :d=>'d', :f=>{:x=>'x'}}}
)
assert_flattens({:a=>{:b =>['a', 'b']}, :"a.b"=>['a', 'b']}, {:a=>{:b =>['a', 'b']}})
assert_flattens({:"a\001b" => "c"}, {:"a.b" => "c"})
assert_flattens({:"a.b"=>['a', 'b']}, {:a=>{:b =>['a', 'b']}}, true, false)
assert_flattens({:"a.b" => "c"}, {:"a.b" => "c"}, false)
end
test "store_translations supports numeric keys" do
setup_backend!
store_translations(:en, 1 => 'foo')
assert_equal 'foo', I18n.t('1')
assert_equal 'foo', I18n.t(1)
assert_equal 'foo', I18n.t(:'1')
end
test "store_translations handle subtrees by default" do
setup_backend!
assert_equal({ :bar => 'bar', :baz => 'baz' }, I18n.t("foo"))
end
test "store_translations merge subtrees accordingly" do
setup_backend!
store_translations(:en, :foo => { :baz => "BAZ"})
assert_equal('BAZ', I18n.t("foo.baz"))
assert_equal({ :bar => 'bar', :baz => 'BAZ' }, I18n.t("foo"))
end
test "store_translations does not handle subtrees if desired" do
setup_backend!(false)
assert_raises I18n::MissingTranslationData do
I18n.t("foo", :raise => true)
end
end
test 'initialized? checks that a store is available' do
setup_backend!
I18n.backend.reload!
assert_equal I18n.backend.initialized?, true
end
test 'translations gets the translations from the store' do
setup_backend!
I18n.backend.send(:translations)
expected = { :en => {:foo => { :bar => 'bar', :baz => 'baz' }} }
assert_equal expected, translations
end
test "subtrees enabled: given incomplete pluralization data it raises I18n::InvalidPluralizationData" do
setup_backend!
store_translations(:en, :bar => { :one => "One" })
assert_raises(I18n::InvalidPluralizationData) { I18n.t(:bar, :count => 2) }
end
test "subtrees disabled: given incomplete pluralization data it returns an error message" do
setup_backend!(false)
store_translations(:en, :bar => { :one => "One" })
assert_equal "Translation missing: en.bar", I18n.t(:bar, :count => 2)
end
test "translate handles subtrees for pluralization" do
setup_backend!(false)
store_translations(:en, :bar => { :one => "One" })
assert_equal("One", I18n.t("bar", :count => 1))
end
test "subtrees enabled: returns localized string given missing pluralization data" do
setup_backend!(true)
assert_equal 'bar', I18n.t("foo.bar", count: 1)
end
test "subtrees disabled: returns localized string given missing pluralization data" do
setup_backend!(false)
assert_equal 'bar', I18n.t("foo.bar", count: 1)
end
test "subtrees enabled: Returns fallback default given missing pluralization data" do
setup_backend!(true)
I18n.backend.extend I18n::Backend::Fallbacks
assert_equal 'default', I18n.t(:missing_bar, count: 1, default: 'default')
assert_equal 'default', I18n.t(:missing_bar, count: 0, default: 'default')
end
test "subtrees disabled: Returns fallback default given missing pluralization data" do
setup_backend!(false)
I18n.backend.extend I18n::Backend::Fallbacks
assert_equal 'default', I18n.t(:missing_bar, count: 1, default: 'default')
assert_equal 'default', I18n.t(:missing_bar, count: 0, default: 'default')
end
end if I18n::TestCase.key_value?
i18n-1.14.7/test/backend/lazy_loadable_test.rb 0000664 0000000 0000000 00000016364 14743300461 0021133 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nBackendLazyLoadableTest < I18n::TestCase
def setup
super
@lazy_mode_backend = I18n::Backend::LazyLoadable.new(lazy_load: true)
@eager_mode_backend = I18n::Backend::LazyLoadable.new(lazy_load: false)
I18n.load_path = [File.join(locales_dir, '/en.yml'), File.join(locales_dir, '/en.yaml'), File.join(locales_dir, '/fr.yml')]
end
test "lazy mode: only loads translations for current locale" do
with_lazy_mode do
@backend.reload!
assert_nil translations
I18n.with_locale(:en) { I18n.t("foo.bar") }
assert_equal({ en: { foo: { bar: "baz" }}}, translations)
end
end
test "lazy mode: merges translations for current locale with translations already existing in memory" do
with_lazy_mode do
@backend.reload!
I18n.with_locale(:en) { I18n.t("foo.bar") }
assert_equal({ en: { foo: { bar: "baz" }}}, translations)
I18n.with_locale(:fr) { I18n.t("animal.dog") }
assert_equal({ en: { foo: { bar: "baz" } }, fr: { animal: { dog: "chien" } } }, translations)
end
end
test "lazy mode: #initialized? responds based on whether current locale is initialized" do
with_lazy_mode do
@backend.reload!
I18n.with_locale(:en) do
refute_predicate @backend, :initialized?
I18n.t("foo.bar")
assert_predicate @backend, :initialized?
end
I18n.with_locale(:fr) do
refute_predicate @backend, :initialized?
end
end
end
test "lazy mode: reload! uninitializes all locales" do
with_lazy_mode do
I18n.with_locale(:en) { I18n.t("foo.bar") }
I18n.with_locale(:fr) { I18n.t("animal.dog") }
@backend.reload!
I18n.with_locale(:en) do
refute_predicate @backend, :initialized?
end
I18n.with_locale(:fr) do
refute_predicate @backend, :initialized?
end
end
end
test "lazy mode: eager_load! raises UnsupportedMethod exception" do
with_lazy_mode do
exception = assert_raises(I18n::UnsupportedMethod) { @backend.eager_load! }
expected_msg = "I18n::Backend::LazyLoadable does not support the #eager_load! method. Cannot eager load translations because backend was configured with lazy_load: true."
assert_equal expected_msg, exception.message
end
end
test "lazy mode: loads translations from files that start with current locale identifier" do
with_lazy_mode do
file_contents = { en: { alice: "bob" } }.to_yaml
invalid_files = [
{ filename: ['translation', '.yml'] }, # No locale identifier
{ filename: ['translation', '.unsupported'] }, # No locale identifier and unsupported extension
]
invalid_files.each do |file|
with_translation_file_in_load_path(file[:filename], file[:dir], file_contents) do
I18n.with_locale(:en) { I18n.t("foo.bar") }
assert_equal({ en: { foo: { bar: "baz" }}}, translations)
end
end
valid_files = [
{ filename: ['en_translation', '.yml'] }, # Contains locale identifier with correct demarcation, and supported extension
{ filename: ['en_', '.yml'] }, # Path component matches locale identifier exactly
]
valid_files.each do |file|
with_translation_file_in_load_path(file[:filename], file[:dir], file_contents) do
I18n.with_locale(:en) { I18n.t("foo.bar") }
assert_equal({ en: { foo: { bar: "baz" }, alice: "bob" }}, translations)
end
end
end
end
test "lazy mode: files with unsupported extensions raise UnknownFileType error" do
with_lazy_mode do
file_contents = { en: { alice: "bob" } }.to_yaml
filename = ['en_translation', '.unsupported'] # Correct locale identifier, but unsupported extension
with_translation_file_in_load_path(filename, nil, file_contents) do
assert_raises(I18n::UnknownFileType) { I18n.t("foo.bar") }
end
end
end
test "lazy mode: #available_locales returns all locales available from load path irrespective of current locale" do
with_lazy_mode do
I18n.with_locale(:en) { assert_equal [:en, :fr], @backend.available_locales }
I18n.with_locale(:fr) { assert_equal [:en, :fr], @backend.available_locales }
end
end
test "lazy mode: raises error if translations loaded don't correspond to locale extracted from filename" do
filename = ["en_", ".yml"]
file_contents = { fr: { dog: "chien" } }.to_yaml
with_lazy_mode do
with_translation_file_in_load_path(filename, nil, file_contents) do |file_path|
exception = assert_raises(I18n::InvalidFilenames) { I18n.t("foo.bar") }
expected_message = /#{Regexp.escape(file_path)} can only load translations for "en"\. Found translations for: \[\:fr\]/
assert_match expected_message, exception.message
end
end
end
test "lazy mode: raises error if translations for more than one locale are loaded from a single file" do
filename = ["en_", ".yml"]
file_contents = { en: { alice: "bob" }, fr: { dog: "chien" }, de: { cat: 'katze' } }.to_yaml
with_lazy_mode do
with_translation_file_in_load_path(filename, nil, file_contents) do |file_path|
exception = assert_raises(I18n::InvalidFilenames) { I18n.t("foo.bar") }
expected_message = /#{Regexp.escape(file_path)} can only load translations for "en"\. Found translations for: \[\:fr\, \:de\]/
assert_match expected_message, exception.message
end
end
end
test "lazy mode: #lookup lazy loads translations for supplied locale" do
with_lazy_mode do
@backend.reload!
assert_nil translations
I18n.with_locale(:en) do
assert_equal "chien", @backend.lookup(:fr, "animal.dog")
end
assert_equal({ fr: { animal: { dog: "chien" } } }, translations)
end
end
test "eager mode: load all translations, irrespective of locale" do
with_eager_mode do
@backend.reload!
assert_nil translations
I18n.with_locale(:en) { I18n.t("foo.bar") }
assert_equal({ en: { foo: { bar: "baz" } }, fr: { animal: { dog: "chien" } } }, translations)
end
end
test "eager mode: raises error if locales loaded cannot be extracted from load path names" do
with_eager_mode do
@backend.reload!
contents = { de: { cat: 'katze' } }.to_yaml
with_translation_file_in_load_path(['fr_translation', '.yml'], nil, contents) do |file_path|
exception = assert_raises(I18n::InvalidFilenames) { I18n.t("foo.bar") }
expected_message = /#{Regexp.escape(file_path)} can only load translations for "fr"\. Found translations for: \[\:de\]/
assert_match expected_message, exception.message
end
end
end
private
def with_lazy_mode
@backend = I18n.backend = @lazy_mode_backend
yield
end
def with_eager_mode
@backend = I18n.backend = @eager_mode_backend
yield
end
def with_translation_file_in_load_path(name, tmpdir, file_contents)
@backend.reload!
path_to_dir = FileUtils.mkdir_p(File.join(Dir.tmpdir, tmpdir)).first if tmpdir
locale_file = Tempfile.new(name, path_to_dir)
locale_file.write(file_contents)
locale_file.rewind
I18n.load_path << locale_file.path
yield(locale_file.path)
I18n.load_path.delete(locale_file.path)
end
end
i18n-1.14.7/test/backend/memoize_test.rb 0000664 0000000 0000000 00000004527 14743300461 0017774 0 ustar 00root root 0000000 0000000 require 'test_helper'
require 'backend/simple_test'
class I18nBackendMemoizeTest < I18nBackendSimpleTest
module MemoizeSpy
attr_accessor :spy_calls
def available_locales
self.spy_calls = (self.spy_calls || 0) + 1
super
end
end
class MemoizeBackend < I18n::Backend::Simple
include MemoizeSpy
include I18n::Backend::Memoize
end
def setup
super
I18n.backend = MemoizeBackend.new
end
def test_memoizes_available_locales
I18n.backend.spy_calls = 0
assert_equal I18n.available_locales, I18n.available_locales
assert_equal 1, I18n.backend.spy_calls
end
def test_resets_available_locales_on_reload!
I18n.available_locales
I18n.backend.spy_calls = 0
I18n.reload!
assert_equal I18n.available_locales, I18n.available_locales
assert_equal 1, I18n.backend.spy_calls
end
def test_resets_available_locales_on_store_translations
I18n.available_locales
I18n.backend.spy_calls = 0
I18n.backend.store_translations(:copa, :ca => :bana)
assert_equal I18n.available_locales, I18n.available_locales
assert I18n.available_locales.include?(:copa)
assert_equal 1, I18n.backend.spy_calls
end
def test_eager_load
I18n.eager_load!
I18n.backend.spy_calls = 0
assert_equal I18n.available_locales, I18n.available_locales
assert_equal 0, I18n.backend.spy_calls
end
module TestLookup
def lookup(locale, key, scope = [], options = {})
keys = I18n.normalize_keys(locale, key, scope, options[:separator])
keys.inspect
end
end
def test_lookup_concurrent_consistency
backend_impl = Class.new(I18n::Backend::Simple) do
include TestLookup
include I18n::Backend::Memoize
end
backend = backend_impl.new
memoized_lookup = backend.send(:memoized_lookup)
assert_equal "[:foo, :scoped, :sample]", backend.translate('foo', scope = [:scoped, :sample])
30.times.inject([]) do |memo, i|
memo << Thread.new do
backend.translate('bar', scope); backend.translate(:baz, scope)
end
end.each(&:join)
memoized_lookup = backend.send(:memoized_lookup)
puts memoized_lookup.inspect if $VERBOSE
assert_equal 3, memoized_lookup.size, "NON-THREAD-SAFE lookup memoization backend: #{memoized_lookup.class}"
# if a plain Hash is used might eventually end up in a weird (inconsistent) state
end
end
i18n-1.14.7/test/backend/metadata_test.rb 0000664 0000000 0000000 00000003202 14743300461 0020074 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nBackendMetadataTest < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::Metadata
end
def setup
super
I18n.backend = Backend.new
store_translations(:en, :foo => 'Hi %{name}')
end
test "translation strings carry metadata" do
translation = I18n.t(:foo, :name => 'David')
assert translation.respond_to?(:translation_metadata)
assert translation.translation_metadata.is_a?(Hash)
end
test "translate adds the locale to metadata on Strings" do
assert_equal :en, I18n.t(:foo, :name => 'David', :locale => :en).translation_metadata[:locale]
end
test "translate adds the key to metadata on Strings" do
assert_equal :foo, I18n.t(:foo, :name => 'David').translation_metadata[:key]
end
test "translate adds the default to metadata on Strings" do
assert_equal 'bar', I18n.t(:foo, :default => 'bar', :name => '').translation_metadata[:default]
end
test "translation adds the interpolation values to metadata on Strings" do
assert_equal({:name => 'David'}, I18n.t(:foo, :name => 'David').translation_metadata[:values])
end
test "interpolation adds the original string to metadata on Strings" do
assert_equal('Hi %{name}', I18n.t(:foo, :name => 'David').translation_metadata[:original])
end
test "pluralization adds the count to metadata on Strings" do
assert_equal(1, I18n.t(:missing, :count => 1, :default => { :one => 'foo' }).translation_metadata[:count])
end
test "metadata works with frozen values" do
assert_equal(1, I18n.t(:missing, :count => 1, :default => 'foo'.freeze).translation_metadata[:count])
end
end
i18n-1.14.7/test/backend/pluralization_fallback_test.rb 0000664 0000000 0000000 00000004732 14743300461 0023041 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nBackendPluralizationFallbackTest < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::Pluralization
include I18n::Backend::Fallbacks
end
def setup
super
I18n.default_locale = :'en'
I18n.backend = Backend.new
store_translations('en', cat: { zero: 'cat', one: 'cat', other: 'cats' })
store_translations('en-US', cat: { zero: 'no cat', one: nil, other: 'lots of cats' })
store_translations('ru', cat: { one: 'кот', few: 'кошек', many: 'кошка', other: 'кошек' })
# probably not a real locale but just to demonstrate
store_translations('ru-US', cat: { one: nil, few: nil, many: nil, other: nil })
store_translations('ru', i18n: { plural: { rule: russian_rule }})
end
test "fallbacks: nils are ignored and fallback is applied" do
assert_equal "no cat", I18n.t("cat", count: 0, locale: "en-US")
assert_equal "cat", I18n.t("cat", count: 0, locale: "en")
assert_equal "cat", I18n.t("cat", count: 1, locale: "en-US")
assert_equal "cat", I18n.t("cat", count: 1, locale: "en")
assert_equal "lots of cats", I18n.t("cat", count: 2, locale: "en-US")
assert_equal "cats", I18n.t("cat", count: 2, locale: "en")
end
test "fallbacks: nils are ignored and fallback is applied, with custom rule" do
# more specs: https://github.com/svenfuchs/rails-i18n/blob/master/spec/unit/pluralization/east_slavic.rb
assert_equal "кошка", I18n.t("cat", count: 0, locale: "ru")
assert_equal "кошка", I18n.t("cat", count: 0, locale: "ru-US")
assert_equal "кот", I18n.t("cat", count: 1, locale: "ru")
assert_equal "кот", I18n.t("cat", count: 1, locale: "ru-US")
assert_equal "кошек", I18n.t("cat", count: 2, locale: "ru")
assert_equal "кошек", I18n.t("cat", count: 2, locale: "ru-US")
assert_equal "кошек", I18n.t("cat", count: 1.5, locale: "ru")
assert_equal "кошек", I18n.t("cat", count: 1.5, locale: "ru-US")
end
private
# copied from https://github.com/svenfuchs/rails-i18n/blob/master/lib/rails_i18n/common_pluralizations/east_slavic.rb
def russian_rule
lambda do |n|
n ||= 0
mod10 = n % 10
mod100 = n % 100
if mod10 == 1 && mod100 != 11
:one
elsif (2..4).include?(mod10) && !(12..14).include?(mod100)
:few
elsif mod10 == 0 || (5..9).include?(mod10) || (11..14).include?(mod100)
:many
else
:other
end
end
end
end
i18n-1.14.7/test/backend/pluralization_scope_test.rb 0000664 0000000 0000000 00000002226 14743300461 0022407 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nBackendPluralizationScopeTest < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::Pluralization
include I18n::Backend::Fallbacks
end
def setup
super
I18n.default_locale = :'en'
I18n.backend = Backend.new
translations = {
i18n: {
plural: {
keys: [:one, :other],
rule: lambda { |n| n == 1 ? :one : :other },
}
},
activerecord: {
models: {
my_model: {
one: 'one model',
other: 'more models',
some_other_key: {
key: 'value'
}
}
}
}
}
store_translations('en', translations)
end
test "pluralization picks :other for 2" do
args = {
scope: [:activerecord, :models],
count: 2,
default: ["My model"]
}
assert_equal 'more models', I18n.translate(:my_model, **args)
end
test "pluralization picks :one for 1" do
args = {
scope: [:activerecord, :models],
count: 1,
default: ["My model"]
}
assert_equal 'one model', I18n.translate(:my_model, **args)
end
end
i18n-1.14.7/test/backend/pluralization_test.rb 0000664 0000000 0000000 00000007714 14743300461 0021225 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nBackendPluralizationTest < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::Pluralization
include I18n::Backend::Fallbacks
end
def setup
super
I18n.backend = Backend.new
@rule = lambda { |n| n % 10 == 1 && n % 100 != 11 ? :one : n == 0 || (2..10).include?(n % 100) ? :few : (11..19).include?(n % 100) ? :many : :other }
store_translations(:xx, :i18n => { :plural => { :rule => @rule } })
@entry = { :"0" => 'none', :"1" => 'single', :one => 'one', :few => 'few', :many => 'many', :other => 'other' }
@entry_with_zero = @entry.merge( { :zero => 'zero' } )
end
test "pluralization picks a pluralizer from :'i18n.pluralize'" do
assert_equal @rule, I18n.backend.send(:pluralizer, :xx)
end
test "pluralization picks the explicit 1 rule for count == 1, the explicit rule takes priority over the matching :one rule" do
assert_equal 'single', I18n.t(:count => 1, :default => @entry, :locale => :xx)
assert_equal 'single', I18n.t(:count => 1.0, :default => @entry, :locale => :xx)
end
test "pluralization picks :one for 1, since in this case that is the matching rule for 1 (when there is no explicit 1 rule)" do
@entry.delete(:"1")
assert_equal 'one', I18n.t(:count => 1, :default => @entry, :locale => :xx)
end
test "pluralization picks :few for 2" do
assert_equal 'few', I18n.t(:count => 2, :default => @entry, :locale => :xx)
end
test "pluralization picks :many for 11" do
assert_equal 'many', I18n.t(:count => 11, :default => @entry, :locale => :xx)
end
test "pluralization picks zero for 0 if the key is contained in the data" do
assert_equal 'zero', I18n.t(:count => 0, :default => @entry_with_zero, :locale => :xx)
end
test "pluralization picks explicit 0 rule for count == 0, since the explicit rule takes priority over the matching :few rule" do
assert_equal 'none', I18n.t(:count => 0, :default => @entry, :locale => :xx)
assert_equal 'none', I18n.t(:count => 0.0, :default => @entry, :locale => :xx)
assert_equal 'none', I18n.t(:count => -0, :default => @entry, :locale => :xx)
end
test "pluralization picks :few for 0 (when there is no explicit 0 rule)" do
@entry.delete(:"0")
assert_equal 'few', I18n.t(:count => 0, :default => @entry, :locale => :xx)
end
test "pluralization does Lateral Inheritance to :other to cover missing data" do
@entry.delete(:many)
assert_equal 'other', I18n.t(:count => 11, :default => @entry, :locale => :xx)
end
test "pluralization picks one for 1 if the entry has attributes hash on unknown locale" do
@entry[:attributes] = { :field => 'field', :second => 'second' }
assert_equal 'one', I18n.t(:count => 1, :default => @entry, :locale => :pirate)
end
test "Nested keys within pluralization context" do
store_translations(:xx,
:stars => {
one: "%{count} star",
other: "%{count} stars",
special: {
one: "%{count} special star",
other: "%{count} special stars",
}
}
)
assert_equal "1 star", I18n.t('stars', count: 1, :locale => :xx)
assert_equal "20 stars", I18n.t('stars', count: 20, :locale => :xx)
assert_equal "1 special star", I18n.t('stars.special', count: 1, :locale => :xx)
assert_equal "20 special stars", I18n.t('stars.special', count: 20, :locale => :xx)
end
test "Fallbacks can pick up rules from fallback locales, too" do
assert_equal @rule, I18n.backend.send(:pluralizer, :'xx-XX')
end
test "linked lookup works with pluralization backend" do
I18n.backend.store_translations(:xx, {
:automobiles => :autos,
:autos => :cars,
:cars => { :porsche => { :one => "I have %{count} Porsche 🚗", :other => "I have %{count} Porsches 🚗" } }
})
assert_equal "I have 1 Porsche 🚗", I18n.t(:'automobiles.porsche', count: 1, :locale => :xx)
assert_equal "I have 20 Porsches 🚗", I18n.t(:'automobiles.porsche', count: 20, :locale => :xx)
end
end
i18n-1.14.7/test/backend/simple_test.rb 0000664 0000000 0000000 00000021760 14743300461 0017616 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nBackendSimpleTest < I18n::TestCase
def setup
super
I18n.backend = I18n::Backend::Simple.new
I18n.load_path = [locales_dir + '/en.yml']
end
# useful because this way we can use the backend with no key for interpolation/pluralization
test "simple backend translate: given nil as a key it still interpolations the default value" do
assert_equal "Hi David", I18n.t(nil, :default => "Hi %{name}", :name => "David")
end
test "simple backend translate: given true as a key" do
store_translations :en, available: { true => "Yes", false => "No" }
assert_equal "Yes", I18n.t(:available)[true]
assert_equal "No", I18n.t(:available)[false]
end
test "simple backend translate: given integer as a key" do
store_translations :en, available: { -1 => "Possibly", 0 => "Maybe", 1 => "Yes", 2 => "No", 3 => "Never" }
assert_equal "Possibly", I18n.t(:available)[-1]
assert_equal "Possibly", I18n.t('available.-1')
assert_equal "Maybe", I18n.t(:available)[0]
assert_equal "Maybe", I18n.t('available.0')
assert_equal "Yes", I18n.t(:available)[1]
assert_equal "Yes", I18n.t('available.1')
assert_equal "No", I18n.t(:available)[2]
assert_equal "No", I18n.t('available.2')
assert_equal "Never", I18n.t(:available)[3]
assert_equal "Never", I18n.t('available.+3')
end
test 'simple backend translate: given integer with a leading positive/negative sign' do
store_translations :en, available: { -1 => "No", 0 => "Maybe", 1 => "Yes" }
assert_equal 'No', I18n.t(:available)[-1]
assert_equal 'No', I18n.t('available.-1')
assert_equal 'Maybe', I18n.t(:available)[+0]
assert_equal 'Maybe', I18n.t(:available)[-0]
assert_equal 'Maybe', I18n.t('available.-0')
assert_equal 'Maybe', I18n.t('available.+0')
assert_equal 'Yes', I18n.t(:available)[+1]
assert_equal 'Yes', I18n.t('available.+1')
end
test 'simple backend translate: given integer with a lead zero as a key' do
store_translations :en, available: { '01' => 'foo' }
assert_equal 'foo', I18n.t(:available)[:'01']
assert_equal 'foo', I18n.t('available.01')
end
test "simple backend translate: symbolize keys in hash" do
store_translations :en, nested_hashes_in_array: { hello: "world" }
assert_equal "world", I18n.t('nested_hashes_in_array.hello')
assert_equal "world", I18n.t('nested_hashes_in_array')[:hello]
end
test "simple backend translate: symbolize keys in array" do
store_translations :en, nested_hashes_in_array: [ { hello: "world" } ]
I18n.t('nested_hashes_in_array').each do |val|
assert_equal "world", val[:hello]
end
end
# loading translations
test "simple load_translations: given an unknown file type it raises I18n::UnknownFileType" do
assert_raises(I18n::UnknownFileType) { I18n.backend.load_translations("#{locales_dir}/en.xml") }
end
test "simple load_translations: given a YAML file name with yaml extension does not raise anything" do
assert_nothing_raised { I18n.backend.load_translations("#{locales_dir}/en.yaml") }
end
test "simple load_translations: given a JSON file name with yaml extension does not raise anything" do
assert_nothing_raised { I18n.backend.load_translations("#{locales_dir}/en.json") }
end
test "simple load_translations: given a Ruby file name it does not raise anything" do
assert_nothing_raised { I18n.backend.load_translations("#{locales_dir}/en.rb") }
end
test "simple load_translations: given no argument, it uses I18n.load_path" do
I18n.backend.load_translations
assert_equal({ :en => { :foo => { :bar => 'baz' } } }, I18n.backend.send(:translations))
end
test "simple load_rb: loads data from a Ruby file" do
data, _ = I18n.backend.send(:load_rb, "#{locales_dir}/en.rb")
assert_equal({ :en => { :fuh => { :bah => 'bas' } } }, data)
end
test "simple load_yml: loads data from a YAML file" do
data, _ = I18n.backend.send(:load_yml, "#{locales_dir}/en.yml")
if ::YAML.respond_to?(:unsafe_load_file)
assert_equal({ :en => { :foo => { :bar => 'baz' } } }, data)
assert_predicate data.dig(:en, :foo, :bar), :frozen?
else
assert_equal({ 'en' => { 'foo' => { 'bar' => 'baz' } } }, data)
end
end
test "simple load_json: loads data from a JSON file" do
data, _ = I18n.backend.send(:load_json, "#{locales_dir}/en.json")
if JSON.respond_to?(:load_file)
assert_equal({ :en => { :foo => { :bar => 'baz' } } }, data)
assert_predicate data.dig(:en, :foo, :bar), :frozen?
else
assert_equal({ 'en' => { 'foo' => { 'bar' => 'baz' } } }, data)
end
end
test "simple load_translations: loads data from known file formats" do
I18n.backend = I18n::Backend::Simple.new
I18n.backend.load_translations("#{locales_dir}/en.rb", "#{locales_dir}/en.yml")
expected = { :en => { :fuh => { :bah => "bas" }, :foo => { :bar => "baz" } } }
assert_equal expected, translations
end
test "simple load_translations: given file names as array it does not raise anything" do
assert_nothing_raised { I18n.backend.load_translations(["#{locales_dir}/en.rb", "#{locales_dir}/en.yml"]) }
end
# storing translations
test "simple store_translations: stores translations, ... no, really :-)" do
store_translations :'en', :foo => 'bar'
assert_equal Hash[:'en', {:foo => 'bar'}], translations
end
test "simple store_translations: deep_merges with existing translations" do
store_translations :'en', :foo => {:bar => 'bar'}
store_translations :'en', :foo => {:baz => 'baz'}
assert_equal Hash[:'en', {:foo => {:bar => 'bar', :baz => 'baz'}}], translations
end
test "simple store_translations: converts the given locale to a Symbol" do
store_translations 'en', :foo => 'bar'
assert_equal Hash[:'en', {:foo => 'bar'}], translations
end
test "simple store_translations: converts keys to Symbols" do
store_translations 'en', 'foo' => {'bar' => 'bar', 'baz' => 'baz'}
assert_equal Hash[:'en', {:foo => {:bar => 'bar', :baz => 'baz'}}], translations
end
test "simple store_translations: do not store translations unavailable locales if enforce_available_locales is true" do
begin
I18n.enforce_available_locales = true
I18n.available_locales = [:en, :es]
store_translations(:fr, :foo => {:bar => 'barfr', :baz => 'bazfr'})
store_translations(:es, :foo => {:bar => 'bares', :baz => 'bazes'})
assert_equal translations[:fr], {}
assert_equal Hash[:foo, {:bar => 'bares', :baz => 'bazes'}], translations[:es]
ensure
I18n.config.enforce_available_locales = false
end
end
test "simple store_translations: store translations for unavailable locales if enforce_available_locales is false" do
I18n.available_locales = [:en, :es]
store_translations(:fr, :foo => {:bar => 'barfr', :baz => 'bazfr'})
assert_equal Hash[:foo, {:bar => 'barfr', :baz => 'bazfr'}], translations[:fr]
end
test "simple store_translations: supports numeric keys" do
store_translations(:en, 1 => 'foo')
assert_equal 'foo', I18n.t('1')
assert_equal 'foo', I18n.t(1)
assert_equal 'foo', I18n.t(:'1')
end
test "simple store_translations: store translations doesn't deep symbolize keys if skip_symbolize_keys is true" do
data = { :foo => {'bar' => 'barfr', 'baz' => 'bazfr'} }
# symbolized by default
store_translations(:fr, data)
assert_equal Hash[:foo, {:bar => 'barfr', :baz => 'bazfr'}], translations[:fr]
I18n.backend.reload!
# not deep symbolized when configured
store_translations(:fr, data, skip_symbolize_keys: true)
assert_equal Hash[:foo, {'bar' => 'barfr', 'baz' => 'bazfr'}], translations[:fr]
end
# reloading translations
test "simple reload_translations: unloads translations" do
I18n.backend.reload!
assert_nil translations
end
test "simple reload_translations: uninitializes the backend" do
I18n.backend.reload!
assert_equal false, I18n.backend.initialized?
end
test "simple eager_load!: loads the translations" do
assert_equal false, I18n.backend.initialized?
I18n.backend.eager_load!
assert_equal true, I18n.backend.initialized?
end
test "simple reload!: reinitialize the backend if it was previously eager loaded" do
I18n.backend.eager_load!
I18n.backend.reload!
assert_equal true, I18n.backend.initialized?
end
test "Nested keys within pluralization context" do
store_translations(:en,
:stars => {
one: "%{count} star",
other: "%{count} stars",
special: {
one: "%{count} special star",
other: "%{count} special stars",
}
}
)
assert_equal "1 star", I18n.t('stars', count: 1, :locale => :en)
assert_equal "20 stars", I18n.t('stars', count: 20, :locale => :en)
assert_equal "1 special star", I18n.t('stars.special', count: 1, :locale => :en)
assert_equal "20 special stars", I18n.t('stars.special', count: 20, :locale => :en)
end
test "returns localized string given missing pluralization data" do
assert_equal 'baz', I18n.t('foo.bar', count: 1)
end
end
i18n-1.14.7/test/backend/transliterator_test.rb 0000664 0000000 0000000 00000006031 14743300461 0021374 0 ustar 00root root 0000000 0000000 # encoding: utf-8
require 'test_helper'
class I18nBackendTransliterator < I18n::TestCase
def setup
super
I18n.backend = I18n::Backend::Simple.new
@proc = lambda { |n| n.upcase }
@hash = { "ü" => "ue", "ö" => "oe", "a" => "a" }
@transliterator = I18n::Backend::Transliterator.get
end
test "transliteration rule can be a proc" do
store_translations(:xx, :i18n => {:transliterate => {:rule => @proc}})
assert_equal "HELLO", I18n.backend.transliterate(:xx, "hello")
end
test "transliteration rule can be a hash" do
store_translations(:xx, :i18n => {:transliterate => {:rule => @hash}})
assert_equal "ue", I18n.backend.transliterate(:xx, "ü")
end
test "transliteration rule must be a proc or hash" do
store_translations(:xx, :i18n => {:transliterate => {:rule => ""}})
assert_raises I18n::ArgumentError do
I18n.backend.transliterate(:xx, "ü")
end
end
test "transliterator defaults to latin => ascii when no rule is given" do
assert_equal "AEroskobing", I18n.backend.transliterate(:xx, "Ærøskøbing")
end
test "default transliterator should not modify ascii characters" do
(0..127).each do |byte|
char = [byte].pack("U")
assert_equal char, @transliterator.transliterate(char)
end
end
test "default transliterator correctly transliterates latin characters" do
# create string with range of Unicode's western characters with
# diacritics, excluding the division and multiplication signs which for
# some reason or other are floating in the middle of all the letters.
string = (0xC0..0x17E).to_a.reject {|c| [0xD7, 0xF7].include? c}.append(0x1E9E).pack("U*")
string.split(//) do |char|
assert_match %r{^[a-zA-Z']*$}, @transliterator.transliterate(string)
end
end
test "should replace non-ASCII chars not in map with a replacement char" do
assert_equal "abc?", @transliterator.transliterate("abcſ")
end
test "can replace non-ASCII chars not in map with a custom replacement string" do
assert_equal "abc#", @transliterator.transliterate("abcſ", "#")
end
test "default transliterator raises errors for invalid UTF-8" do
assert_raises ArgumentError do
@transliterator.transliterate("a\x92b")
end
end
test "I18n.transliterate should transliterate using a default transliterator" do
assert_equal "aeo", I18n.transliterate("áèö")
end
test "I18n.transliterate should transliterate using a locale" do
store_translations(:xx, :i18n => {:transliterate => {:rule => @hash}})
assert_equal "ue", I18n.transliterate("ü", :locale => :xx)
end
test "default transliterator fails with custom rules with uncomposed input" do
char = [117, 776].pack("U*") # "ü" as ASCII "u" plus COMBINING DIAERESIS
transliterator = I18n::Backend::Transliterator.get(@hash)
refute_equal "ue", transliterator.transliterate(char)
end
test "DEFAULT_APPROXIMATIONS is frozen to prevent concurrency issues" do
assert I18n::Backend::Transliterator::HashTransliterator::DEFAULT_APPROXIMATIONS.frozen?
end
end
i18n-1.14.7/test/gettext/ 0000775 0000000 0000000 00000000000 14743300461 0015030 5 ustar 00root root 0000000 0000000 i18n-1.14.7/test/gettext/api_test.rb 0000664 0000000 0000000 00000021021 14743300461 0017161 0 ustar 00root root 0000000 0000000 # encoding: utf-8
require 'test_helper'
require 'i18n/gettext/helpers'
include I18n::Gettext::Helpers
class I18nGettextApiTest < I18n::TestCase
def setup
super
I18n.locale = :en
I18n.backend.store_translations :de, {
'Hi Gettext!' => 'Hallo Gettext!',
'Sentence 1. Sentence 2.' => 'Satz 1. Satz 2.',
"An apple" => { :one => 'Ein Apfel', :other => '%{count} Äpfel' },
:special => { "A special apple" => { :one => 'Ein spezieller Apfel', :other => '%{count} spezielle Äpfel' } },
:foo => { :bar => 'bar-de' },
'foo.bar' => 'Foo Bar'
}, :separator => '|'
end
# N_
def test_N_returns_original_msg
assert_equal 'foo|bar', N_('foo|bar')
I18n.locale = :de
assert_equal 'Hi Gettext!', N_('Hi Gettext!')
end
# gettext
def test_gettext_uses_msg_as_default
assert_equal 'Hi Gettext!', _('Hi Gettext!')
end
def test_gettext_uses_msg_as_key
I18n.locale = :de
assert_equal 'Hallo Gettext!', gettext('Hi Gettext!')
assert_equal 'Hallo Gettext!', _('Hi Gettext!')
end
def test_gettext_uses_msg_containing_dots_as_default
assert_equal 'Sentence 1. Sentence 2.', gettext('Sentence 1. Sentence 2.')
assert_equal 'Sentence 1. Sentence 2.', _('Sentence 1. Sentence 2.')
end
def test_gettext_uses_msg_containing_dots_as_key
I18n.locale = :de
assert_equal 'Satz 1. Satz 2.', gettext('Sentence 1. Sentence 2.')
assert_equal 'Satz 1. Satz 2.', _('Sentence 1. Sentence 2.')
end
# sgettext
def test_sgettext_defaults_to_the_last_token_of_a_scoped_msgid
assert_equal 'bar', sgettext('foo|bar')
assert_equal 'bar', s_('foo|bar')
end
def test_sgettext_looks_up_a_scoped_translation
I18n.locale = :de
assert_equal 'bar-de', sgettext('foo|bar')
assert_equal 'bar-de', s_('foo|bar')
end
def test_sgettext_ignores_dots
I18n.locale = :de
assert_equal 'Foo Bar', sgettext('foo.bar')
assert_equal 'Foo Bar', s_('foo.bar')
end
# pgettext
def test_pgettext_defaults_to_msgid
assert_equal 'bar', pgettext('foo', 'bar')
assert_equal 'bar', p_('foo', 'bar')
end
def test_pgettext_looks_up_a_scoped_translation
I18n.locale = :de
assert_equal 'bar-de', pgettext('foo', 'bar')
assert_equal 'bar-de', p_('foo', 'bar')
end
# ngettext
def test_ngettext_looks_up_msg_id_as_default_singular
assert_equal 'An apple', ngettext('An apple', '%{count} apples', 1)
assert_equal 'An apple', n_('An apple', '%{count} apples', 1)
end
def test_ngettext_looks_up_msg_id_plural_as_default_plural
assert_equal '2 apples', ngettext('An apple', '%{count} apples', 2)
assert_equal '2 apples', n_('An apple', '%{count} apples', 2)
end
def test_ngettext_looks_up_a_singular
I18n.locale = :de
assert_equal 'Ein Apfel', ngettext('An apple', '%{count} apples', 1)
assert_equal 'Ein Apfel', n_('An apple', '%{count} apples', 1)
end
def test_ngettext_looks_up_a_plural
I18n.locale = :de
assert_equal '2 Äpfel', ngettext('An apple', '%{count} apples', 2)
assert_equal '2 Äpfel', n_('An apple', '%{count} apples', 2)
end
def test_ngettext_looks_up_msg_id_as_default_singular_with_alternative_syntax
assert_equal 'An apple', ngettext(['An apple', '%{count} apples'], 1)
assert_equal 'An apple', n_(['An apple', '%{count} apples'], 1)
end
def test_ngettext_looks_up_msg_id_plural_as_default_plural_with_alternative_syntax
assert_equal '2 apples', ngettext(['An apple', '%{count} apples'], 2)
assert_equal '2 apples', n_(['An apple', '%{count} apples'], 2)
end
def test_ngettext_looks_up_a_singular_with_alternative_syntax
I18n.locale = :de
assert_equal 'Ein Apfel', ngettext(['An apple', '%{count} apples'], 1)
assert_equal 'Ein Apfel', n_(['An apple', '%{count} apples'], 1)
end
def test_ngettext_looks_up_a_plural_with_alternative_syntax
I18n.locale = :de
assert_equal '2 Äpfel', ngettext(['An apple', '%{count} apples'], 2)
assert_equal '2 Äpfel', n_(['An apple', '%{count} apples'], 2)
end
# nsgettext
def test_nsgettext_looks_up_msg_id_as_default_singular
assert_equal 'A special apple', nsgettext('special|A special apple', '%{count} special apples', 1)
assert_equal 'A special apple', ns_('special|A special apple', '%{count} special apples', 1)
end
def test_nsgettext_looks_up_msg_id_plural_as_default_plural
assert_equal '2 special apples', nsgettext('special|A special apple', '%{count} special apples', 2)
assert_equal '2 special apples', ns_('special|A special apple', '%{count} special apples', 2)
end
def test_nsgettext_looks_up_a_singular
I18n.locale = :de
assert_equal 'Ein spezieller Apfel', nsgettext('special|A special apple', '%{count} special apples', 1)
assert_equal 'Ein spezieller Apfel', ns_('special|A special apple', '%{count} special apples', 1)
end
def test_nsgettext_looks_up_a_plural
I18n.locale = :de
assert_equal '2 spezielle Äpfel', nsgettext('special|A special apple', '%{count} special apples', 2)
assert_equal '2 spezielle Äpfel', ns_('special|A special apple', '%{count} special apples', 2)
end
def test_nsgettext_looks_up_msg_id_as_default_singular_with_alternative_syntax
assert_equal 'A special apple', nsgettext(['special|A special apple', '%{count} special apples'], 1)
assert_equal 'A special apple', ns_(['special|A special apple', '%{count} special apples'], 1)
end
def test_nsgettext_looks_up_msg_id_plural_as_default_plural_with_alternative_syntax
assert_equal '2 special apples', nsgettext(['special|A special apple', '%{count} special apples'], 2)
assert_equal '2 special apples', ns_(['special|A special apple', '%{count} special apples'], 2)
end
def test_nsgettext_looks_up_a_singular_with_alternative_syntax
I18n.locale = :de
assert_equal 'Ein spezieller Apfel', nsgettext(['special|A special apple', '%{count} special apples'], 1)
assert_equal 'Ein spezieller Apfel', ns_(['special|A special apple', '%{count} special apples'], 1)
end
def test_nsgettext_looks_up_a_plural_with_alternative_syntax
I18n.locale = :de
assert_equal '2 spezielle Äpfel', nsgettext(['special|A special apple', '%{count} special apples'], 2)
assert_equal '2 spezielle Äpfel', ns_(['special|A special apple', '%{count} special apples'], 2)
end
# npgettext
def test_npgettext_looks_up_msg_id_as_default_singular
assert_equal 'A special apple', npgettext('special', 'A special apple', '%{count} special apples', 1)
assert_equal 'A special apple', np_('special', 'A special apple', '%{count} special apples', 1)
end
def test_npgettext_looks_up_msg_id_plural_as_default_plural
assert_equal '2 special apples', npgettext('special', 'A special apple', '%{count} special apples', 2)
assert_equal '2 special apples', np_('special', 'A special apple', '%{count} special apples', 2)
end
def test_npgettext_looks_up_a_singular
I18n.locale = :de
assert_equal 'Ein spezieller Apfel', npgettext('special', 'A special apple', '%{count} special apples', 1)
assert_equal 'Ein spezieller Apfel', np_('special', 'A special apple', '%{count} special apples', 1)
end
def test_npgettext_looks_up_a_plural
I18n.locale = :de
assert_equal '2 spezielle Äpfel', npgettext('special', 'A special apple', '%{count} special apples', 2)
assert_equal '2 spezielle Äpfel', np_('special', 'A special apple', '%{count} special apples', 2)
end
def test_npgettext_looks_up_msg_id_as_default_singular_with_alternative_syntax
assert_equal 'A special apple', npgettext('special', ['A special apple', '%{count} special apples'], 1)
assert_equal 'A special apple', np_('special', ['A special apple', '%{count} special apples'], 1)
end
def test_npgettext_looks_up_msg_id_plural_as_default_plural_with_alternative_syntax
assert_equal '2 special apples', npgettext('special', ['A special apple', '%{count} special apples'], 2)
assert_equal '2 special apples', np_('special', ['A special apple', '%{count} special apples'], 2)
end
def test_npgettext_looks_up_a_singular_with_alternative_syntax
I18n.locale = :de
assert_equal 'Ein spezieller Apfel', npgettext('special', ['A special apple', '%{count} special apples'], 1)
assert_equal 'Ein spezieller Apfel', np_('special', ['A special apple', '%{count} special apples'], 1)
end
def test_npgettext_looks_up_a_plural_with_alternative_syntax
I18n.locale = :de
assert_equal '2 spezielle Äpfel', npgettext('special', ['A special apple', '%{count} special apples'], 2)
assert_equal '2 spezielle Äpfel', np_('special', ['A special apple', '%{count} special apples'], 2)
end
end
i18n-1.14.7/test/gettext/backend_test.rb 0000664 0000000 0000000 00000006154 14743300461 0020011 0 ustar 00root root 0000000 0000000 # encoding: utf-8
require 'test_helper'
class I18nGettextBackendTest < I18n::TestCase
include I18n::Gettext::Helpers
class Backend < I18n::Backend::Simple
include I18n::Backend::Gettext
end
def setup
super
I18n.backend = Backend.new
I18n.locale = :en
I18n.load_path = ["#{locales_dir}/de.po"]
I18n.default_separator = '|'
end
def test_backend_loads_po_file
I18n.backend.send(:init_translations)
assert I18n.backend.send(:translations)[:de][:"Axis"]
end
def test_looks_up_a_translation
I18n.locale = :de
assert_equal 'Auto', gettext('car')
end
def test_uses_default_translation
assert_equal 'car', gettext('car')
end
def test_looks_up_a_namespaced_translation
I18n.locale = :de
assert_equal 'Räderzahl', sgettext('Car|Wheels count')
assert_equal 'Räderzahl', pgettext('Car', 'Wheels count')
assert_equal 'Räderzahl!', pgettext('New car', 'Wheels count')
end
def test_uses_namespaced_default_translation
assert_equal 'Wheels count', sgettext('Car|Wheels count')
assert_equal 'Wheels count', pgettext('Car', 'Wheels count')
assert_equal 'Wheels count', pgettext('New car', 'Wheels count')
end
def test_pluralizes_entry
I18n.locale = :de
assert_equal 'Achse', ngettext('Axis', 'Axis', 1)
assert_equal 'Achsen', ngettext('Axis', 'Axis', 2)
end
def test_pluralizes_default_entry
assert_equal 'Axis', ngettext('Axis', 'Axis', 1)
assert_equal 'Axis', ngettext('Axis', 'Axis', 2)
end
def test_pluralizes_namespaced_entry
I18n.locale = :de
assert_equal 'Rad', nsgettext('Car|wheel', 'wheels', 1)
assert_equal 'Räder', nsgettext('Car|wheel', 'wheels', 2)
assert_equal 'Rad', npgettext('Car', 'wheel', 'wheels', 1)
assert_equal 'Räder', npgettext('Car', 'wheel', 'wheels', 2)
assert_equal 'Rad!', npgettext('New car', 'wheel', 'wheels', 1)
assert_equal 'Räder!', npgettext('New car', 'wheel', 'wheels', 2)
end
def test_pluralizes_namespaced_default_entry
assert_equal 'wheel', nsgettext('Car|wheel', 'wheels', 1)
assert_equal 'wheels', nsgettext('Car|wheel', 'wheels', 2)
assert_equal 'wheel', npgettext('Car', 'wheel', 'wheels', 1)
assert_equal 'wheels', npgettext('Car', 'wheel', 'wheels', 2)
assert_equal 'wheel', npgettext('New car', 'wheel', 'wheels', 1)
assert_equal 'wheels', npgettext('New car', 'wheel', 'wheels', 2)
end
def test_pluralizes_namespaced_entry_with_alternative_syntax
I18n.locale = :de
assert_equal 'Rad', nsgettext(['Car|wheel', 'wheels'], 1)
assert_equal 'Räder', nsgettext(['Car|wheel', 'wheels'], 2)
assert_equal 'Rad', npgettext('Car', ['wheel', 'wheels'], 1)
assert_equal 'Räder', npgettext('Car', ['wheel', 'wheels'], 2)
assert_equal 'Rad!', npgettext('New car', ['wheel', 'wheels'], 1)
assert_equal 'Räder!', npgettext('New car', ['wheel', 'wheels'], 2)
end
def test_ngettextpluralizes_entry_with_dots
I18n.locale = :de
assert_equal 'Auf 1 Achse.', n_("On %{count} wheel.", "On %{count} wheels.", 1)
assert_equal 'Auf 2 Achsen.', n_("On %{count} wheel.", "On %{count} wheels.", 2)
end
end
i18n-1.14.7/test/i18n/ 0000775 0000000 0000000 00000000000 14743300461 0014123 5 ustar 00root root 0000000 0000000 i18n-1.14.7/test/i18n/exceptions_test.rb 0000664 0000000 0000000 00000007552 14743300461 0017701 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nExceptionsTest < I18n::TestCase
def test_invalid_locale_stores_locale
force_invalid_locale
rescue I18n::ArgumentError => exception
assert_nil exception.locale
end
test "passing an invalid locale raises an InvalidLocale exception" do
force_invalid_locale do |exception|
assert_equal 'nil is not a valid locale', exception.message
end
end
test "MissingTranslation can be initialized without options" do
exception = I18n::MissingTranslation.new(:en, 'foo')
assert_equal({}, exception.options)
end
test "MissingTranslationData exception stores locale, key and options" do
force_missing_translation_data do |exception|
assert_equal 'de', exception.locale
assert_equal :foo, exception.key
assert_equal({:scope => :bar}, exception.options)
end
end
test "MissingTranslationData message contains the locale and scoped key" do
force_missing_translation_data do |exception|
assert_equal 'translation missing: de.bar.foo', exception.message
end
end
test "InvalidPluralizationData stores entry, count and key" do
force_invalid_pluralization_data do |exception|
assert_equal({:other => "bar"}, exception.entry)
assert_equal 1, exception.count
assert_equal :one, exception.key
end
end
test "InvalidPluralizationData message contains count, data and missing key" do
force_invalid_pluralization_data do |exception|
assert_match '1', exception.message
assert_match %|#{{:other=>"bar"}}|, exception.message
assert_match 'one', exception.message
end
end
test "MissingInterpolationArgument stores key and string" do
assert_raises(I18n::MissingInterpolationArgument) { force_missing_interpolation_argument }
force_missing_interpolation_argument do |exception|
assert_equal :bar, exception.key
assert_equal "%{bar}", exception.string
end
end
test "MissingInterpolationArgument message contains the missing and given arguments" do
force_missing_interpolation_argument do |exception|
assert_equal %|missing interpolation argument :bar in "%{bar}" (#{{:baz=>"baz"}.to_s} given)|, exception.message
end
end
test "ReservedInterpolationKey stores key and string" do
force_reserved_interpolation_key do |exception|
assert_equal :scope, exception.key
assert_equal "%{scope}", exception.string
end
end
test "ReservedInterpolationKey message contains the reserved key" do
force_reserved_interpolation_key do |exception|
assert_equal 'reserved key :scope used in "%{scope}"', exception.message
end
end
test "MissingTranslationData#new can be initialized with just two arguments" do
assert I18n::MissingTranslationData.new('en', 'key')
end
private
def force_invalid_locale
I18n.translate(:foo, :locale => nil)
rescue I18n::ArgumentError => e
block_given? ? yield(e) : raise(e)
end
def force_missing_translation_data(options = {})
store_translations('de', :bar => nil)
I18n.translate(:foo, **options.merge(:scope => :bar, :locale => :de))
rescue I18n::ArgumentError => e
block_given? ? yield(e) : raise(e)
end
def force_invalid_pluralization_data
store_translations('de', :foo => { :other => 'bar' })
I18n.translate(:foo, :count => 1, :locale => :de)
rescue I18n::ArgumentError => e
block_given? ? yield(e) : raise(e)
end
def force_missing_interpolation_argument
store_translations('de', :foo => "%{bar}")
I18n.translate(:foo, :baz => 'baz', :locale => :de)
rescue I18n::ArgumentError => e
block_given? ? yield(e) : raise(e)
end
def force_reserved_interpolation_key
store_translations('de', :foo => "%{scope}")
I18n.translate(:foo, :baz => 'baz', :locale => :de)
rescue I18n::ArgumentError => e
block_given? ? yield(e) : raise(e)
end
end
i18n-1.14.7/test/i18n/gettext_plural_keys_test.rb 0000664 0000000 0000000 00000001131 14743300461 0021601 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nGettextPluralKeysTest < I18n::TestCase
def setup
super
I18n::Gettext.plural_keys[:zz] = [:value1, :value2]
end
test "Returns the plural keys of the given locale if present" do
assert_equal I18n::Gettext.plural_keys(:zz), [:value1, :value2]
end
test "Returns the plural keys of :en if given locale not present" do
assert_equal I18n::Gettext.plural_keys(:yy), [:one, :other]
end
test "Returns the whole hash with no arguments" do
assert_equal I18n::Gettext.plural_keys, { :en => [:one, :other], :zz => [:value1, :value2] }
end
end
i18n-1.14.7/test/i18n/interpolate_test.rb 0000664 0000000 0000000 00000011065 14743300461 0020040 0 ustar 00root root 0000000 0000000 require 'test_helper'
# thanks to Masao's String extensions, some tests taken from Masao's tests
# http://github.com/mutoh/gettext/blob/edbbe1fa8238fa12c7f26f2418403015f0270e47/test/test_string.rb
class I18nInterpolateTest < I18n::TestCase
test "String interpolates a hash argument w/ named placeholders" do
assert_equal "Masao Mutoh", I18n.interpolate("%{first} %{last}", :first => 'Masao', :last => 'Mutoh' )
end
test "String interpolates a hash argument w/ named placeholders (reverse order)" do
assert_equal "Mutoh, Masao", I18n.interpolate("%{last}, %{first}", :first => 'Masao', :last => 'Mutoh' )
end
test "String interpolates named placeholders with sprintf syntax" do
assert_equal "10, 43.4", I18n.interpolate("%d, %.1f", :integer => 10, :float => 43.4)
end
test "String interpolates named placeholders with sprintf syntax, does not recurse" do
assert_equal "%s", I18n.interpolate("%{msg}", :msg => '%s', :not_translated => 'should not happen' )
end
test "String interpolation does not replace anything when no placeholders are given" do
assert_equal "aaa", I18n.interpolate("aaa", :num => 1)
end
test "String interpolation sprintf behaviour equals Ruby 1.9 behaviour" do
assert_equal "1", I18n.interpolate("%d", :num => 1)
assert_equal "0b1", I18n.interpolate("%#b", :num => 1)
assert_equal "foo", I18n.interpolate("%s", :msg => "foo")
assert_equal "1.000000", I18n.interpolate("%f", :num => 1.0)
assert_equal " 1", I18n.interpolate("%3.0f", :num => 1.0)
assert_equal "100.00", I18n.interpolate("%2.2f", :num => 100.0)
assert_equal "0x64", I18n.interpolate("%#x", :num => 100.0)
assert_raises(ArgumentError) { I18n.interpolate("%,d", :num => 100) }
assert_raises(ArgumentError) { I18n.interpolate("%/d", :num => 100) }
end
test "String interpolation raises an I18n::MissingInterpolationArgument when the string has extra placeholders" do
assert_raises(I18n::MissingInterpolationArgument, "key not found") do
I18n.interpolate("%{first} %{last}", :first => 'Masao')
end
end
test "String interpolation does not raise when extra values were passed" do
assert_nothing_raised do
assert_equal "Masao Mutoh", I18n.interpolate("%{first} %{last}", :first => 'Masao', :last => 'Mutoh', :salutation => 'Mr.' )
end
end
test "% acts as escape character in String interpolation" do
assert_equal "%{first}", I18n.interpolate("%%{first}", :first => 'Masao')
assert_equal "% 1", I18n.interpolate("%% %d", :num => 1.0)
assert_equal "%{num} %d", I18n.interpolate("%%{num} %%d", :num => 1)
end
def test_sprintf_mix_unformatted_and_formatted_named_placeholders
assert_equal "foo 1.000000", I18n.interpolate("%{name} %f", :name => "foo", :num => 1.0)
end
class RailsSafeBuffer < String
def gsub(*args, &block)
to_str.gsub(*args, &block)
end
end
test "with String subclass that redefined gsub method" do
assert_equal "Hello mars world", I18n.interpolate(RailsSafeBuffer.new("Hello %{planet} world"), :planet => 'mars')
end
test "with String subclass that redefined gsub method returns same object if no interpolations" do
string = RailsSafeBuffer.new("Hello world")
assert_same string, I18n.interpolate(string, :planet => 'mars')
end
end
class I18nMissingInterpolationCustomHandlerTest < I18n::TestCase
def setup
super
@old_handler = I18n.config.missing_interpolation_argument_handler
I18n.config.missing_interpolation_argument_handler = lambda do |key, values, string|
"missing key is #{key}, values are #{values.inspect}, given string is '#{string}'"
end
end
def teardown
I18n.config.missing_interpolation_argument_handler = @old_handler
super
end
test "String interpolation can use custom missing interpolation handler" do
assert_equal %|Masao missing key is last, values are #{{:first=>"Masao"}.to_s}, given string is '%{first} %{last}'|,
I18n.interpolate("%{first} %{last}", :first => 'Masao')
end
end
class I18nCustomInterpolationPatternTest < I18n::TestCase
def setup
super
@old_interpolation_patterns = I18n.config.interpolation_patterns
I18n.config.interpolation_patterns << /\{\{(\w+)\}\}/
end
def teardown
I18n.config.interpolation_patterns = @old_interpolation_patterns
super
end
test "String interpolation can use custom interpolation pattern" do
assert_equal "Masao Mutoh", I18n.interpolate("{{first}} {{last}}", :first => "Masao", :last => "Mutoh")
end
end
i18n-1.14.7/test/i18n/load_path_test.rb 0000664 0000000 0000000 00000002657 14743300461 0017454 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nLoadPathTest < I18n::TestCase
def setup
super
I18n.locale = :en
I18n.backend = I18n::Backend::Simple.new
store_translations(:en, :foo => {:bar => 'bar', :baz => 'baz'})
end
test "nested load paths do not break locale loading" do
I18n.load_path = [[locales_dir + '/en.yml']]
assert_equal "baz", I18n.t(:'foo.bar')
end
test "loading an empty yml file raises an InvalidLocaleData exception" do
assert_raises I18n::InvalidLocaleData do
I18n.load_path = [[locales_dir + '/invalid/empty.yml']]
I18n.t(:'foo.bar', :default => "baz")
end
end
test "loading an invalid yml file raises an InvalidLocaleData exception" do
assert_raises I18n::InvalidLocaleData do
I18n.load_path = [[locales_dir + '/invalid/syntax.yml']]
I18n.t(:'foo.bar', :default => "baz")
end
end
test "adding arrays of filenames to the load path does not break locale loading" do
I18n.load_path << Dir[locales_dir + '/*.{rb,yml}']
assert_equal "baz", I18n.t(:'foo.bar')
end
test "adding Pathnames to the load path does not break YML file locale loading" do
I18n.load_path << Pathname.new(locales_dir + '/en.yml')
assert_equal "baz", I18n.t(:'foo.bar')
end
test "adding Pathnames to the load path does not break Ruby file locale loading" do
I18n.load_path << Pathname.new(locales_dir + '/en.rb')
assert_equal "bas", I18n.t(:'fuh.bah')
end
end
i18n-1.14.7/test/i18n/middleware_test.rb 0000664 0000000 0000000 00000001240 14743300461 0017621 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nMiddlewareTest < I18n::TestCase
def setup
super
I18n.default_locale = :fr
@app = DummyRackApp.new
@middleware = I18n::Middleware.new(@app)
end
test "middleware initializes new config object after request" do
old_i18n_config_object_id = Thread.current[:i18n_config].object_id
@middleware.call({})
updated_i18n_config_object_id = Thread.current[:i18n_config].object_id
refute_equal updated_i18n_config_object_id, old_i18n_config_object_id
end
test "successfully resets i18n locale to default locale by defining new config" do
@middleware.call({})
assert_equal :fr, I18n.locale
end
end
i18n-1.14.7/test/i18n_test.rb 0000664 0000000 0000000 00000044756 14743300461 0015527 0 ustar 00root root 0000000 0000000 # encoding: utf-8
require 'test_helper'
class I18nTest < I18n::TestCase
def setup
super
store_translations(:en, :currency => { :format => { :separator => '.', :delimiter => ',', } })
store_translations(:nl, :currency => { :format => { :separator => ',', :delimiter => '.', } })
store_translations(:en, "true" => "Yes", "false" => "No")
end
test "exposes its VERSION constant" do
assert I18n::VERSION
end
test "uses the simple backend by default" do
assert I18n.backend.is_a?(I18n::Backend::Simple)
end
test "can set the backend" do
begin
assert_nothing_raised { I18n.backend = self }
assert_equal self, I18n.backend
ensure
I18n.backend = I18n::Backend::Simple.new
end
end
test "uses :en as a default_locale by default" do
assert_equal :en, I18n.default_locale
end
test "can set the default locale" do
begin
assert_nothing_raised { I18n.default_locale = 'de' }
assert_equal :de, I18n.default_locale
ensure
I18n.default_locale = :en
end
end
test "default_locale= doesn't ignore junk" do
assert_raises(NoMethodError) { I18n.default_locale = Class }
end
test "raises an I18n::InvalidLocale exception when setting an unavailable default locale" do
begin
I18n.config.enforce_available_locales = true
assert_raises(I18n::InvalidLocale) { I18n.default_locale = :klingon }
ensure
I18n.config.enforce_available_locales = false
end
end
test "uses the default locale as a locale by default" do
assert_equal I18n.default_locale, I18n.locale
end
test "sets the current locale to Thread.current" do
assert_nothing_raised { I18n.locale = 'de' }
assert_equal :de, I18n.locale
assert_equal :de, Thread.current[:i18n_config].locale
I18n.locale = :en
end
test "locale= doesn't ignore junk" do
assert_raises(NoMethodError) { I18n.locale = Class }
end
test "raises an I18n::InvalidLocale exception when setting an unavailable locale" do
begin
I18n.config.enforce_available_locales = true
assert_raises(I18n::InvalidLocale) { I18n.locale = :klingon }
ensure
I18n.config.enforce_available_locales = false
end
end
test "can set the configuration object" do
begin
I18n.config = self
assert_equal self, I18n.config
assert_equal self, Thread.current[:i18n_config]
ensure
I18n.config = ::I18n::Config.new
end
end
test "locale is not shared between configurations" do
a = I18n::Config.new
b = I18n::Config.new
a.locale = :fr
b.locale = :es
assert_equal :fr, a.locale
assert_equal :es, b.locale
assert_equal :en, I18n.locale
end
test "other options are shared between configurations" do
begin
a = I18n::Config.new
b = I18n::Config.new
a.default_locale = :fr
b.default_locale = :es
assert_equal :es, a.default_locale
assert_equal :es, b.default_locale
assert_equal :es, I18n.default_locale
ensure
I18n.default_locale = :en
end
end
test "uses a dot as a default_separator by default" do
assert_equal '.', I18n.default_separator
end
test "can set the default_separator" do
begin
assert_nothing_raised { I18n.default_separator = "\001" }
ensure
I18n.default_separator = '.'
end
end
test "normalize_keys normalizes given locale, keys and scope to an array of single-key symbols" do
assert_equal [:en, :foo, :bar], I18n.normalize_keys(:en, :bar, :foo)
assert_equal [:en, :foo, :bar, :baz, :buz], I18n.normalize_keys(:en, :'baz.buz', :'foo.bar')
assert_equal [:en, :foo, :bar, :baz, :buz], I18n.normalize_keys(:en, 'baz.buz', 'foo.bar')
assert_equal [:en, :foo, :bar, :baz, :buz], I18n.normalize_keys(:en, %w(baz buz), %w(foo bar))
assert_equal [:en, :foo, :bar, :baz, :buz], I18n.normalize_keys(:en, [:baz, :buz], [:foo, :bar])
end
test "normalize_keys discards empty keys" do
assert_equal [:en, :foo, :bar, :baz, :buz], I18n.normalize_keys(:en, :'baz..buz', :'foo..bar')
assert_equal [:en, :foo, :bar, :baz, :buz], I18n.normalize_keys(:en, :'baz......buz', :'foo......bar')
assert_equal [:en, :foo, :bar, :baz, :buz], I18n.normalize_keys(:en, ['baz', nil, '', 'buz'], ['foo', nil, '', 'bar'])
end
test "normalize_keys uses a given separator" do
assert_equal [:en, :foo, :bar, :baz, :buz], I18n.normalize_keys(:en, :'baz|buz', :'foo|bar', '|')
end
test "normalize_keys normalizes given locale with separator" do
assert_equal [:en, :foo, :bar, :baz], I18n.normalize_keys(:"en.foo", :baz, :bar)
end
test "can set the exception_handler" do
begin
previous_exception_handler = I18n.exception_handler
assert_nothing_raised { I18n.exception_handler = :custom_exception_handler }
ensure
I18n.exception_handler = previous_exception_handler
end
end
test "uses a custom exception handler set to I18n.exception_handler" do
begin
previous_exception_handler = I18n.exception_handler
I18n.exception_handler = :custom_exception_handler
I18n.expects(:custom_exception_handler)
I18n.translate :bogus
ensure
I18n.exception_handler = previous_exception_handler
end
end
test "uses a custom exception handler passed as an option" do
I18n.expects(:custom_exception_handler)
I18n.translate(:bogus, :exception_handler => :custom_exception_handler)
end
test "delegates translate calls to the backend" do
I18n.backend.expects(:translate).with('de', :foo, {})
I18n.translate :foo, :locale => 'de'
end
test "delegates localize calls to the backend" do
I18n.backend.expects(:localize).with('de', :whatever, :default, {})
I18n.localize :whatever, :locale => 'de'
end
test "translate given no locale uses the current locale" do
I18n.backend.expects(:translate).with(:en, :foo, {})
I18n.translate :foo
end
test "translate works with nested symbol keys" do
assert_equal ".", I18n.t(:'currency.format.separator')
end
test "translate works with nested string keys" do
assert_equal ".", I18n.t('currency.format.separator')
end
test "translate with an array as a scope works" do
assert_equal ".", I18n.t(:separator, :scope => %w(currency format))
end
test "translate with an array containing dot separated strings as a scope works" do
assert_equal ".", I18n.t(:separator, :scope => ['currency.format'])
end
test "translate with an array of keys and a dot separated string as a scope works" do
assert_equal [".", ","], I18n.t(%w(separator delimiter), :scope => 'currency.format')
end
test "translate with an array of dot separated keys and a scope works" do
assert_equal [".", ","], I18n.t(%w(format.separator format.delimiter), :scope => 'currency')
end
# def test_translate_given_no_args_raises_missing_translation_data
# assert_equal "Translation missing: en, no key", I18n.t
# end
test "translate given a bogus key returns an error message" do
assert_equal "Translation missing: en.bogus", I18n.t(:bogus)
end
test "translate given multiple bogus keys returns an array of error messages" do
assert_equal(
["Translation missing: en.bogus", "Translation missing: en.also_bogus"],
I18n.t([:bogus, :also_bogus]),
)
end
test "translate given an empty string as a key raises an I18n::ArgumentError" do
assert_raises(I18n::ArgumentError) { I18n.t("") }
end
test "translate given an empty symbol as a key raises an I18n::ArgumentError" do
assert_raises(I18n::ArgumentError) { I18n.t(:"") }
end
test "translate given an array with empty string as a key raises an I18n::ArgumentError" do
assert_raises(I18n::ArgumentError) { I18n.t(["", :foo]) }
end
test "translate given an empty array as a key returns empty array" do
assert_equal [], I18n.t([])
end
test "translate given nil returns nil" do
assert_nil I18n.t(nil)
end
test "translate given an unavailable locale rases an I18n::InvalidLocale" do
begin
I18n.config.enforce_available_locales = true
assert_raises(I18n::InvalidLocale) { I18n.t(:foo, :locale => 'klingon') }
ensure
I18n.config.enforce_available_locales = false
end
end
test "translate given true as a key works" do
assert_equal "Yes", I18n.t(true)
end
test "translate given false as a key works" do
assert_equal "No", I18n.t(false)
end
test "translate raises Disabled if locale is false" do
I18n.with_locale(false) do
assert_raises I18n::Disabled do
I18n.t('foo')
end
assert_equal 'Translation missing: en.foo', I18n.t('foo', locale: :en)
end
end
test "available_locales can be replaced at runtime" do
begin
I18n.config.enforce_available_locales = true
assert_raises(I18n::InvalidLocale) { I18n.t(:foo, :locale => 'klingon') }
old_locales, I18n.config.available_locales = I18n.config.available_locales, [:klingon]
I18n.t(:foo, :locale => 'klingon')
ensure
I18n.config.enforce_available_locales = false
I18n.config.available_locales = old_locales
end
end
test "available_locales_set should return a set" do
assert_equal Set, I18n.config.available_locales_set.class
assert_equal I18n.config.available_locales.size * 2, I18n.config.available_locales_set.size
end
test "interpolation_keys returns an array of keys" do
store_translations(:en, "example_two" => "Two interpolations %{foo} %{bar}")
assert_equal ["foo", "bar"], I18n.interpolation_keys("example_two")
end
test "interpolation_keys returns an empty array when no interpolations " do
store_translations(:en, "example_zero" => "Zero interpolations")
assert_equal [], I18n.interpolation_keys("example_zero")
end
test "interpolation_keys returns an empty array when missing translation " do
assert_equal [], I18n.interpolation_keys("does-not-exist")
end
test "interpolation_keys returns an empty array when nested translation" do
store_translations(:en, "example_nested" => { "one" => "One %{foo}", "two" => "Two %{bar}" })
assert_equal [], I18n.interpolation_keys("example_nested")
end
test "interpolation_keys returns an array of keys when translation is an Array" do
store_translations(:en, "example_array" => ["One %{foo}", ["Two %{bar}", ["Three %{baz}"]]])
assert_equal ["foo", "bar", "baz"], I18n.interpolation_keys("example_array")
end
test "interpolation_keys raises I18n::ArgumentError when non-string argument" do
assert_raises(I18n::ArgumentError) { I18n.interpolation_keys(["bad-argument"]) }
end
test "exists? given nil raises I18n::ArgumentError" do
assert_raises(I18n::ArgumentError) { I18n.exists?(nil) }
end
test "exists? given an existing key will return true" do
assert_equal true, I18n.exists?(:currency)
end
test "exists? given a non-existing key will return false" do
assert_equal false, I18n.exists?(:bogus)
end
test "exists? given an existing dot-separated key will return true" do
assert_equal true, I18n.exists?('currency.format.delimiter')
end
test "exists? given a non-existing dot-separated key will return false" do
assert_equal false, I18n.exists?('currency.format.bogus')
end
test "exists? given an existing key and an existing locale will return true" do
assert_equal true, I18n.exists?(:currency, :nl)
end
test "exists? given an existing key and a scope will return true" do
assert_equal true, I18n.exists?(:delimiter, scope: [:currency, :format])
end
test "exists? given a non-existing key and an existing locale will return false" do
assert_equal false, I18n.exists?(:bogus, :nl)
end
test "exists? raises Disabled if locale is false" do
I18n.with_locale(false) do
assert_raises I18n::Disabled do
I18n.exists?(:bogus)
end
assert_equal false, I18n.exists?(:bogus, :nl)
end
end
test "localize given nil raises an I18n::ArgumentError" do
assert_raises(I18n::ArgumentError) { I18n.l nil }
end
test "localize given nil and default returns default" do
assert_nil I18n.l(nil, :default => nil)
end
test "localize given an Object raises an I18n::ArgumentError" do
assert_raises(I18n::ArgumentError) { I18n.l Object.new }
end
test "localize given an unavailable locale rases an I18n::InvalidLocale" do
begin
I18n.config.enforce_available_locales = true
assert_raises(I18n::InvalidLocale) { I18n.l(Time.now, :locale => 'klingon') }
ensure
I18n.config.enforce_available_locales = false
end
end
test "localize raises Disabled if locale is false" do
I18n.with_locale(false) do
assert_raises I18n::Disabled do
I18n.l(Time.now)
end
end
end
test "can use a lambda as an exception handler" do
begin
previous_exception_handler = I18n.exception_handler
I18n.exception_handler = Proc.new { |exception, locale, key, options| key }
assert_equal :test_proc_handler, I18n.translate(:test_proc_handler)
ensure
I18n.exception_handler = previous_exception_handler
end
end
test "can use an object responding to #call as an exception handler" do
begin
previous_exception_handler = I18n.exception_handler
I18n.exception_handler = Class.new do
def call(exception, locale, key, options); key; end
end.new
assert_equal :test_proc_handler, I18n.translate(:test_proc_handler)
ensure
I18n.exception_handler = previous_exception_handler
end
end
test "I18n.with_locale temporarily sets the given locale" do
store_translations(:en, :foo => 'Foo in :en')
store_translations(:de, :foo => 'Foo in :de')
store_translations(:pl, :foo => 'Foo in :pl')
I18n.with_locale { assert_equal [:en, 'Foo in :en'], [I18n.locale, I18n.t(:foo)] }
I18n.with_locale(:de) { assert_equal [:de, 'Foo in :de'], [I18n.locale, I18n.t(:foo)] }
I18n.with_locale(:pl) { assert_equal [:pl, 'Foo in :pl'], [I18n.locale, I18n.t(:foo)] }
I18n.with_locale(:en) { assert_equal [:en, 'Foo in :en'], [I18n.locale, I18n.t(:foo)] }
assert_equal I18n.default_locale, I18n.locale
end
test "I18n.with_locale resets the locale in case of errors" do
assert_raises(I18n::ArgumentError) { I18n.with_locale(:pl) { raise I18n::ArgumentError } }
assert_equal I18n.default_locale, I18n.locale
end
test "I18n.transliterate handles I18n::ArgumentError exception" do
I18n::Backend::Transliterator.stubs(:get).raises(I18n::ArgumentError)
I18n.exception_handler.expects(:call).raises(I18n::ArgumentError)
assert_raises(I18n::ArgumentError) {
I18n.transliterate("ąćó")
}
end
test "I18n.transliterate raises I18n::ArgumentError exception" do
I18n::Backend::Transliterator.stubs(:get).raises(I18n::ArgumentError)
I18n.exception_handler.expects(:call).never
assert_raises(I18n::ArgumentError) {
I18n.transliterate("ąćó", :raise => true)
}
end
test "transliterate given an unavailable locale rases an I18n::InvalidLocale" do
begin
I18n.config.enforce_available_locales = true
assert_raises(I18n::InvalidLocale) { I18n.transliterate('string', :locale => 'klingon') }
ensure
I18n.config.enforce_available_locales = false
end
end
test "transliterate non-ASCII chars not in map with default replacement char" do
assert_equal "???", I18n.transliterate("日本語")
end
test "I18n.locale_available? returns true when the passed locale is available" do
I18n.available_locales = [:en, :de]
assert_equal true, I18n.locale_available?(:de)
end
test "I18n.locale_available? returns true when the passed locale is a string and is available" do
I18n.available_locales = [:en, :de]
assert_equal true, I18n.locale_available?('de')
end
test "I18n.locale_available? returns false when the passed locale is unavailable" do
assert_equal false, I18n.locale_available?(:klingon)
end
test "I18n.enforce_available_locales! raises an I18n::InvalidLocale when the passed locale is unavailable" do
begin
I18n.config.enforce_available_locales = true
assert_raises(I18n::InvalidLocale) { I18n.enforce_available_locales!(:klingon) }
ensure
I18n.config.enforce_available_locales = false
end
end
test "I18n.enforce_available_locales! does nothing when the passed locale is available" do
I18n.available_locales = [:en, :de]
begin
I18n.config.enforce_available_locales = true
assert_nothing_raised { I18n.enforce_available_locales!(:en) }
ensure
I18n.config.enforce_available_locales = false
end
end
test "I18n.enforce_available_locales config can be set to false" do
begin
I18n.config.enforce_available_locales = false
assert_equal false, I18n.config.enforce_available_locales
ensure
I18n.config.enforce_available_locales = false
end
end
test 'I18n.reload! reloads the set of locales that are enforced' do
begin
# Clear the backend that affects the available locales and somehow can remain
# set from the last running test.
# For instance, it contains enough translations to cause a false positive with
# this test when ran with --seed=50992
I18n.backend = I18n::Backend::Simple.new
assert !I18n.available_locales.include?(:de), "Available locales should not include :de at this point"
I18n.enforce_available_locales = true
assert_raises(I18n::InvalidLocale) { I18n.default_locale = :de }
assert_raises(I18n::InvalidLocale) { I18n.locale = :de }
store_translations(:de, :foo => 'Foo in :de')
assert_raises(I18n::InvalidLocale) { I18n.default_locale = :de }
assert_raises(I18n::InvalidLocale) { I18n.locale = :de }
I18n.reload!
store_translations(:en, :foo => 'Foo in :en')
store_translations(:de, :foo => 'Foo in :de')
store_translations(:pl, :foo => 'Foo in :pl')
assert I18n.available_locales.include?(:de), ":de should now be allowed"
assert I18n.available_locales.include?(:en), ":en should now be allowed"
assert I18n.available_locales.include?(:pl), ":pl should now be allowed"
assert_nothing_raised { I18n.default_locale = I18n.locale = :en }
assert_nothing_raised { I18n.default_locale = I18n.locale = :de }
assert_nothing_raised { I18n.default_locale = I18n.locale = :pl }
ensure
I18n.enforce_available_locales = false
end
end
test "can reserve a key" do
begin
stub_const(I18n, :RESERVED_KEYS, []) do
I18n.reserve_key(:foo)
I18n.reserve_key("bar")
assert I18n::RESERVED_KEYS.include?(:foo)
assert I18n::RESERVED_KEYS.include?(:bar)
end
ensure
I18n.instance_variable_set(:@reserved_keys_pattern, nil)
end
end
end
i18n-1.14.7/test/locale/ 0000775 0000000 0000000 00000000000 14743300461 0014603 5 ustar 00root root 0000000 0000000 i18n-1.14.7/test/locale/fallbacks_test.rb 0000664 0000000 0000000 00000015403 14743300461 0020114 0 ustar 00root root 0000000 0000000 require 'test_helper'
include I18n::Locale
class I18nFallbacksDefaultsTest < I18n::TestCase
test "defaults to an empty array if no default has been set manually" do
I18n.default_locale = :'en-US'
fallbacks = Fallbacks.new
assert_equal [], fallbacks.defaults
end
test "documentation example #1 - does not use default locale in fallbacks - See Issues #413 & #415" do
I18n.default_locale = :"en-US"
fallbacks = Fallbacks.new(:"de-AT" => :"de-DE")
assert_equal [:"de-AT", :de, :"de-DE"], fallbacks[:"de-AT"]
end
test "documentation example #2 - does not use default locale in fallbacks - Uses custom locale - See Issues #413 & #415" do
I18n.default_locale = :"en-US"
fallbacks = Fallbacks.new(:"en-GB", :"de-AT" => :de, :"de-CH" => :de)
assert_equal [:"de-AT", :de, :"en-GB", :en], fallbacks[:"de-AT"]
assert_equal [:"de-CH", :de, :"en-GB", :en], fallbacks[:"de-CH"]
end
test "explicit fallback to default locale" do
I18n.default_locale = :"en-US"
fallbacks = Fallbacks.new([:"en-US"])
assert_equal [:"de-AT", :de, :"en-US", :en], fallbacks[:"de-AT"]
assert_equal [:"de-CH", :de, :"en-US", :en], fallbacks[:"de-CH"]
end
test "defaults reflect a manually passed default locale if any" do
fallbacks = Fallbacks.new(:'fi-FI')
assert_equal [:'fi-FI', :fi], fallbacks.defaults
I18n.default_locale = :'de-DE'
assert_equal [:'fi-FI', :fi], fallbacks.defaults
end
test "defaults allows to set multiple defaults" do
fallbacks = Fallbacks.new(:'fi-FI', :'se-FI')
assert_equal [:'fi-FI', :fi, :'se-FI', :se], fallbacks.defaults
end
end
class I18nFallbacksComputationTest < I18n::TestCase
def setup
super
@fallbacks = Fallbacks.new(:'en-US')
end
test "with no mappings defined it returns [:es, :en-US] for :es" do
assert_equal [:es, :"en-US", :en], @fallbacks[:es]
end
test "with no mappings defined it returns [:es-ES, :es, :en-US] for :es-ES" do
assert_equal [:"es-ES", :es, :"en-US", :en], @fallbacks[:"es-ES"]
end
test "with no mappings defined it returns [:es-MX, :es, :en-US] for :es-MX" do
assert_equal [:"es-MX", :es, :"en-US", :en], @fallbacks[:"es-MX"]
end
test "with no mappings defined it returns [:es-Latn-ES, :es-Latn, :es, :en-US] for :es-Latn-ES" do
assert_equal [:"es-Latn-ES", :"es-Latn", :es, :"en-US", :en], @fallbacks[:'es-Latn-ES']
end
test "with no mappings defined it returns [:en, :en-US] for :en" do
assert_equal [:en, :"en-US"], @fallbacks[:en]
end
test "with no mappings defined it returns [:en-US, :en] for :en-US (special case: locale == default)" do
assert_equal [:"en-US", :en], @fallbacks[:"en-US"]
end
# Most people who speak Catalan also live in Spain, so it is safe to assume
# that they also speak Spanish as spoken in Spain.
test "with a Catalan mapping defined it returns [:ca, :es-ES, :es, :en-US] for :ca" do
@fallbacks.map(:ca => :"es-ES")
assert_equal [:ca, :"es-ES", :es, :"en-US", :en], @fallbacks[:ca]
end
test "with a Catalan mapping defined it returns [:ca-ES, :ca, :es-ES, :es, :en-US] for :ca-ES" do
@fallbacks.map(:ca => :"es-ES")
assert_equal [:"ca-ES", :ca, :"es-ES", :es, :"en-US", :en], @fallbacks[:"ca-ES"]
end
# People who speak Arabic as spoken in Palestine often times also speak
# Hebrew as spoken in Israel. However it is in no way safe to assume that
# everybody who speaks Arabic also speaks Hebrew.
test "with a Hebrew mapping defined it returns [:ar, :en-US] for :ar" do
@fallbacks.map(:"ar-PS" => :"he-IL")
assert_equal [:ar, :"en-US", :en], @fallbacks[:ar]
end
test "with a Hebrew mapping defined it returns [:ar-EG, :ar, :en-US] for :ar-EG" do
@fallbacks.map(:"ar-PS" => :"he-IL")
assert_equal [:"ar-EG", :ar, :"en-US", :en], @fallbacks[:"ar-EG"]
end
test "with a Hebrew mapping defined it returns [:ar-PS, :ar, :he-IL, :he, :en-US] for :ar-PS" do
@fallbacks.map(:"ar-PS" => :"he-IL")
assert_equal [:"ar-PS", :ar, :"he-IL", :he, :"en-US", :en], @fallbacks[:"ar-PS"]
end
# Sami people live in several scandinavian countries. In Finnland many people
# know Swedish and Finnish. Thus, it can be assumed that Sami living in
# Finnland also speak Swedish and Finnish.
test "with a Sami mapping defined it returns [:sms-FI, :sms, :se-FI, :se, :fi-FI, :fi, :en-US] for :sms-FI" do
@fallbacks.map(:sms => [:"se-FI", :"fi-FI"])
assert_equal [:"sms-FI", :sms, :"se-FI", :se, :"fi-FI", :fi, :"en-US", :en], @fallbacks[:"sms-FI"]
end
# Austrian people understand German as spoken in Germany
test "with a German mapping defined it returns [:de, :en-US] for de" do
@fallbacks.map(:"de-AT" => :"de-DE")
assert_equal [:de, :"en-US", :en], @fallbacks[:"de"]
end
test "with a German mapping defined it returns [:de-DE, :de, :en-US] for de-DE" do
@fallbacks.map(:"de-AT" => :"de-DE")
assert_equal [:"de-DE", :de, :"en-US", :en], @fallbacks[:"de-DE"]
end
test "with a German mapping defined it returns [:de-AT, :de, :de-DE, :en-US] for de-AT" do
@fallbacks.map(:"de-AT" => :"de-DE")
assert_equal [:"de-AT", :de, :"de-DE", :"en-US", :en], @fallbacks[:"de-AT"]
end
# Mapping :de => :en, :he => :en
test "with a mapping :de => :en, :he => :en defined it returns [:de, :en] for :de" do
assert_equal [:de, :"en-US", :en], @fallbacks[:de]
end
test "with a mapping :de => :en, :he => :en defined it [:he, :en] for :de" do
assert_equal [:he, :"en-US", :en], @fallbacks[:he]
end
# Test allowing mappings that fallback to each other
test "with :no => :nb, :nb => :no defined :no returns [:no, :nb, :en-US, :en]" do
@fallbacks.map(:no => :nb, :nb => :no)
assert_equal [:no, :nb, :"en-US", :en], @fallbacks[:no]
end
test "with :no => :nb, :nb => :no defined :nb returns [:nb, :no, :en-US, :en]" do
@fallbacks.map(:no => :nb, :nb => :no)
assert_equal [:nb, :no, :"en-US", :en], @fallbacks[:nb]
end
# Test I18n::Disabled is raised correctly when locale is false during fallback
test "with locale equals false" do
assert_raises I18n::Disabled do
@fallbacks[false]
end
end
end
class I18nFallbacksHashCompatibilityTest < I18n::TestCase
def setup
super
@fallbacks = Fallbacks.new(:'en-US', :"de-AT" => :"de-DE")
end
test "map is compatible with Hash#map" do
result = @fallbacks.map { |key, value| [key, value] }
assert_equal([[:"de-AT", [:"de-DE"]]], result)
end
test "empty? is compatible with Hash#empty?" do
refute_predicate(@fallbacks, :empty?)
refute_predicate(Fallbacks.new(:'en-US'), :empty?)
refute_predicate(Fallbacks.new(:"de-AT" => :"de-DE"), :empty?)
assert_predicate(Fallbacks.new, :empty?)
end
test "#inspect" do
assert_equal(%|#[:"de-DE"]}} @defaults=[:"en-US", :en]>|, @fallbacks.inspect)
end
end
i18n-1.14.7/test/locale/tag/ 0000775 0000000 0000000 00000000000 14743300461 0015356 5 ustar 00root root 0000000 0000000 i18n-1.14.7/test/locale/tag/rfc4646_test.rb 0000664 0000000 0000000 00000012116 14743300461 0020041 0 ustar 00root root 0000000 0000000 # encoding: utf-8
require 'test_helper'
class I18nLocaleTagRfc4646ParserTest < I18n::TestCase
include I18n::Locale
test "Rfc4646::Parser given a valid tag 'de' returns an array of subtags" do
assert_equal ['de', nil, nil, nil, nil, nil, nil], Tag::Rfc4646::Parser.match('de')
end
test "Rfc4646::Parser given a valid tag 'de-DE' returns an array of subtags" do
assert_equal ['de', nil, 'DE', nil, nil, nil, nil], Tag::Rfc4646::Parser.match('de-DE')
end
test "Rfc4646::Parser given a valid lowercase tag 'de-latn-de-variant-x-phonebk' returns an array of subtags" do
assert_equal ['de', 'latn', 'de', 'variant', nil, 'x-phonebk', nil], Tag::Rfc4646::Parser.match('de-latn-de-variant-x-phonebk')
end
test "Rfc4646::Parser given a valid uppercase tag 'DE-LATN-DE-VARIANT-X-PHONEBK' returns an array of subtags" do
assert_equal ['DE', 'LATN', 'DE', 'VARIANT', nil, 'X-PHONEBK', nil], Tag::Rfc4646::Parser.match('DE-LATN-DE-VARIANT-X-PHONEBK')
end
test "Rfc4646::Parser given an invalid tag 'a-DE' it returns false" do
assert_equal false, Tag::Rfc4646::Parser.match('a-DE')
end
test "Rfc4646::Parser given an invalid tag 'de-419-DE' it returns false" do
assert_equal false, Tag::Rfc4646::Parser.match('de-419-DE')
end
end
# Tag for the locale 'de-Latn-DE-Variant-a-ext-x-phonebk-i-klingon'
class I18nLocaleTagSubtagsTest < I18n::TestCase
include I18n::Locale
def setup
super
subtags = %w(de Latn DE variant a-ext x-phonebk i-klingon)
@tag = Tag::Rfc4646.new(*subtags)
end
test "returns 'de' as the language subtag in lowercase" do
assert_equal 'de', @tag.language
end
test "returns 'Latn' as the script subtag in titlecase" do
assert_equal 'Latn', @tag.script
end
test "returns 'DE' as the region subtag in uppercase" do
assert_equal 'DE', @tag.region
end
test "returns 'variant' as the variant subtag in lowercase" do
assert_equal 'variant', @tag.variant
end
test "returns 'a-ext' as the extension subtag" do
assert_equal 'a-ext', @tag.extension
end
test "returns 'x-phonebk' as the privateuse subtag" do
assert_equal 'x-phonebk', @tag.privateuse
end
test "returns 'i-klingon' as the grandfathered subtag" do
assert_equal 'i-klingon', @tag.grandfathered
end
test "returns a formatted tag string from #to_s" do
assert_equal 'de-Latn-DE-variant-a-ext-x-phonebk-i-klingon', @tag.to_s
end
test "returns an array containing the formatted subtags from #to_a" do
assert_equal %w(de Latn DE variant a-ext x-phonebk i-klingon), @tag.to_a
end
end
# Tag inheritance
class I18nLocaleTagSubtagsTest < I18n::TestCase
test "#parent returns 'de-Latn-DE-variant-a-ext-x-phonebk' as the parent of 'de-Latn-DE-variant-a-ext-x-phonebk-i-klingon'" do
tag = Tag::Rfc4646.new(*%w(de Latn DE variant a-ext x-phonebk i-klingon))
assert_equal 'de-Latn-DE-variant-a-ext-x-phonebk', tag.parent.to_s
end
test "#parent returns 'de-Latn-DE-variant-a-ext' as the parent of 'de-Latn-DE-variant-a-ext-x-phonebk'" do
tag = Tag::Rfc4646.new(*%w(de Latn DE variant a-ext x-phonebk))
assert_equal 'de-Latn-DE-variant-a-ext', tag.parent.to_s
end
test "#parent returns 'de-Latn-DE-variant' as the parent of 'de-Latn-DE-variant-a-ext'" do
tag = Tag::Rfc4646.new(*%w(de Latn DE variant a-ext))
assert_equal 'de-Latn-DE-variant', tag.parent.to_s
end
test "#parent returns 'de-Latn-DE' as the parent of 'de-Latn-DE-variant'" do
tag = Tag::Rfc4646.new(*%w(de Latn DE variant))
assert_equal 'de-Latn-DE', tag.parent.to_s
end
test "#parent returns 'de-Latn' as the parent of 'de-Latn-DE'" do
tag = Tag::Rfc4646.new(*%w(de Latn DE))
assert_equal 'de-Latn', tag.parent.to_s
end
test "#parent returns 'de' as the parent of 'de-Latn'" do
tag = Tag::Rfc4646.new(*%w(de Latn))
assert_equal 'de', tag.parent.to_s
end
# TODO RFC4647 says: "If no language tag matches the request, the "default" value is returned."
# where should we set the default language?
# test "#parent returns '' as the parent of 'de'" do
# tag = Tag::Rfc4646.new *%w(de)
# assert_equal '', tag.parent.to_s
# end
test "#parent returns an array of 5 parents for 'de-Latn-DE-variant-a-ext-x-phonebk-i-klingon'" do
parents = %w(de-Latn-DE-variant-a-ext-x-phonebk-i-klingon
de-Latn-DE-variant-a-ext-x-phonebk
de-Latn-DE-variant-a-ext
de-Latn-DE-variant
de-Latn-DE
de-Latn
de)
tag = Tag::Rfc4646.new(*%w(de Latn DE variant a-ext x-phonebk i-klingon))
assert_equal parents, tag.self_and_parents.map(&:to_s)
end
test "returns an array of 5 parents for 'de-Latn-DE-variant-a-ext-x-phonebk-i-klingon'" do
parents = %w(de-Latn-DE-variant-a-ext-x-phonebk-i-klingon
de-Latn-DE-variant-a-ext-x-phonebk
de-Latn-DE-variant-a-ext
de-Latn-DE-variant
de-Latn-DE
de-Latn
de)
tag = Tag::Rfc4646.new(*%w(de Latn DE variant a-ext x-phonebk i-klingon))
assert_equal parents, tag.self_and_parents.map(&:to_s)
end
end
i18n-1.14.7/test/locale/tag/simple_test.rb 0000664 0000000 0000000 00000001772 14743300461 0020242 0 ustar 00root root 0000000 0000000 # encoding: utf-8
require 'test_helper'
class I18nLocaleTagSimpleTest < I18n::TestCase
include I18n::Locale
test "returns 'de' as the language subtag in lowercase" do
assert_equal %w(de Latn DE), Tag::Simple.new('de-Latn-DE').subtags
end
test "returns a formatted tag string from #to_s" do
assert_equal 'de-Latn-DE', Tag::Simple.new('de-Latn-DE').to_s
end
test "returns an array containing the formatted subtags from #to_a" do
assert_equal %w(de Latn DE), Tag::Simple.new('de-Latn-DE').to_a
end
# Tag inheritance
test "#parent returns 'de-Latn' as the parent of 'de-Latn-DE'" do
assert_equal 'de-Latn', Tag::Simple.new('de-Latn-DE').parent.to_s
end
test "#parent returns 'de' as the parent of 'de-Latn'" do
assert_equal 'de', Tag::Simple.new('de-Latn').parent.to_s
end
test "#self_and_parents returns an array of 3 tags for 'de-Latn-DE'" do
assert_equal %w(de-Latn-DE de-Latn de), Tag::Simple.new('de-Latn-DE').self_and_parents.map { |tag| tag.to_s}
end
end
i18n-1.14.7/test/run_all.rb 0000664 0000000 0000000 00000000776 14743300461 0015337 0 ustar 00root root 0000000 0000000 def bundle_check
`bundle check` == "Resolving dependencies...\nThe Gemfile's dependencies are satisfied\n"
end
def execute(command)
puts command
system command
end
gemfiles = %w(Gemfile) + Dir['gemfiles/Gemfile*'].reject { |f| f.end_with?('.lock') }
results = gemfiles.map do |gemfile|
puts "\nBUNDLE_GEMFILE=#{gemfile}"
ENV['BUNDLE_GEMFILE'] = File.expand_path("../../#{gemfile}", __FILE__)
execute 'bundle install' unless bundle_check
execute 'bundle exec rake test'
end
exit results.all?
i18n-1.14.7/test/run_one.rb 0000664 0000000 0000000 00000000417 14743300461 0015340 0 ustar 00root root 0000000 0000000 def bundle_check
`bundle check` == "Resolving dependencies...\nThe Gemfile's dependencies are satisfied\n"
end
def execute(command)
puts command
system command
end
execute 'bundle install' unless bundle_check
execute "bundle exec ruby -w -I'lib:test' #{ARGV[0]}"
i18n-1.14.7/test/test_data/ 0000775 0000000 0000000 00000000000 14743300461 0015314 5 ustar 00root root 0000000 0000000 i18n-1.14.7/test/test_data/locales/ 0000775 0000000 0000000 00000000000 14743300461 0016736 5 ustar 00root root 0000000 0000000 i18n-1.14.7/test/test_data/locales/de.po 0000664 0000000 0000000 00000004004 14743300461 0017664 0 ustar 00root root 0000000 0000000 # SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR , YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: version 0.0.1\n"
"POT-Creation-Date: 2009-02-26 19:50+0100\n"
"PO-Revision-Date: 2009-02-18 14:53+0100\n"
"Last-Translator: FULL NAME \n"
"Language-Team: LANGUAGE \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n"
# #: app/helpers/translation_helper.rb:3
# msgid "%{relative_time} ago"
# msgstr "vor %{relative_time}"
#: app/views/cars/show.html.erb:5
msgid "Axis"
msgid_plural "Axis"
msgstr[0] "Achse"
msgstr[1] "Achsen"
#: app/controllers/cars_controller.rb:47
msgid "Car was successfully created."
msgstr "Auto wurde erfolgreich gespeichert"
#: app/controllers/cars_controller.rb:64
msgid "Car was successfully updated."
msgstr "Auto wurde erfolgreich aktualisiert"
#: app/views/cars/show.html.erb:1 locale/model_attributes.rb:3
msgid "Car|Model"
msgstr "Modell"
#: app/views/cars/show.html.erb:3 locale/model_attributes.rb:4
msgid "Car|Wheels count"
msgstr "Räderzahl"
msgctxt "New car"
msgid "Wheels count"
msgstr "Räderzahl!"
#: app/views/cars/show.html.erb:7
msgid "Created"
msgstr "Erstellt"
#: app/views/cars/show.html.erb:9
msgid "Month"
msgstr "Monat"
#: locale/model_attributes.rb:2
msgid "car"
msgstr "Auto"
#: locale/testlog_phrases.rb:2
msgid "this is a dynamic translation which was found thorugh gettext_test_log!"
msgstr ""
"Dies ist eine dynamische Übersetzung, die durch gettext_test_log "
"gefunden wurde!"
#: app/views/cars/nowhere_really
msgid "Car|wheel"
msgid_plural "Car|wheels"
msgstr[0] "Rad"
msgstr[1] "Räder"
msgctxt "New car"
msgid "wheel"
msgid_plural "wheels"
msgstr[0] "Rad!"
msgstr[1] "Räder!"
msgid "On %{count} wheel."
msgid_plural "On %{count} wheels."
msgstr[0] "Auf %{count} Achse."
msgstr[1] "Auf %{count} Achsen."
i18n-1.14.7/test/test_data/locales/en.json 0000664 0000000 0000000 00000000070 14743300461 0020230 0 ustar 00root root 0000000 0000000 {
"en": {
"foo": {
"bar": "baz"
}
}
}
i18n-1.14.7/test/test_data/locales/en.rb 0000664 0000000 0000000 00000000073 14743300461 0017665 0 ustar 00root root 0000000 0000000 # encoding: utf-8
{ :en => { :fuh => { :bah => "bas" } } } i18n-1.14.7/test/test_data/locales/en.yaml 0000664 0000000 0000000 00000000027 14743300461 0020223 0 ustar 00root root 0000000 0000000 en:
foo:
bar: baz i18n-1.14.7/test/test_data/locales/en.yml 0000664 0000000 0000000 00000000030 14743300461 0020054 0 ustar 00root root 0000000 0000000 en:
foo:
bar: baz
i18n-1.14.7/test/test_data/locales/fr.yml 0000664 0000000 0000000 00000000035 14743300461 0020066 0 ustar 00root root 0000000 0000000 fr:
animal:
dog: chien
i18n-1.14.7/test/test_data/locales/invalid/ 0000775 0000000 0000000 00000000000 14743300461 0020364 5 ustar 00root root 0000000 0000000 i18n-1.14.7/test/test_data/locales/invalid/empty.yml 0000664 0000000 0000000 00000000000 14743300461 0022233 0 ustar 00root root 0000000 0000000 i18n-1.14.7/test/test_data/locales/invalid/syntax.yml 0000664 0000000 0000000 00000000035 14743300461 0022433 0 ustar 00root root 0000000 0000000 en:
foo: foo
bar:
baz: i18n-1.14.7/test/test_data/locales/plurals.rb 0000664 0000000 0000000 00000034412 14743300461 0020751 0 ustar 00root root 0000000 0000000 # encoding: utf-8
{
:af => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:am => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } },
:ar => { :i18n => { :plural => { :keys => [:zero, :one, :two, :few, :many, :other], :rule => lambda { |n| n == 0 ? :zero : n == 1 ? :one : n == 2 ? :two : (3..10).cover?(n % 100) ? :few : (11..99).cover?(n % 100) ? :many : :other } } } },
:az => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } },
:be => { :i18n => { :plural => { :keys => [:one, :few, :many, :other], :rule => lambda { |n| n % 10 == 1 && n % 100 != 11 ? :one : [2, 3, 4].include?(n % 10) && ![12, 13, 14].include?(n % 100) ? :few : n % 10 == 0 || [5, 6, 7, 8, 9].include?(n % 10) || [11, 12, 13, 14].include?(n % 100) ? :many : :other } } } },
:bg => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:bh => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } },
:bn => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:bo => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } },
:bs => { :i18n => { :plural => { :keys => [:one, :few, :many, :other], :rule => lambda { |n| n % 10 == 1 && n % 100 != 11 ? :one : [2, 3, 4].include?(n % 10) && ![12, 13, 14].include?(n % 100) ? :few : n % 10 == 0 || [5, 6, 7, 8, 9].include?(n % 10) || [11, 12, 13, 14].include?(n % 100) ? :many : :other } } } },
:ca => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:cs => { :i18n => { :plural => { :keys => [:one, :few, :other], :rule => lambda { |n| n == 1 ? :one : [2, 3, 4].include?(n) ? :few : :other } } } },
:cy => { :i18n => { :plural => { :keys => [:one, :two, :many, :other], :rule => lambda { |n| n == 1 ? :one : n == 2 ? :two : n == 8 || n == 11 ? :many : :other } } } },
:da => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:de => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:dz => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } },
:el => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:en => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:eo => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:es => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:et => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:eu => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:fa => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } },
:fi => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:fil => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } },
:fo => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:fr => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n.between?(0, 2) && n != 2 ? :one : :other } } } },
:fur => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:fy => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:ga => { :i18n => { :plural => { :keys => [:one, :two, :other], :rule => lambda { |n| n == 1 ? :one : n == 2 ? :two : :other } } } },
:gl => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:gu => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:guw => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } },
:ha => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:he => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:hi => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } },
:hr => { :i18n => { :plural => { :keys => [:one, :few, :many, :other], :rule => lambda { |n| n % 10 == 1 && n % 100 != 11 ? :one : [2, 3, 4].include?(n % 10) && ![12, 13, 14].include?(n % 100) ? :few : n % 10 == 0 || [5, 6, 7, 8, 9].include?(n % 10) || [11, 12, 13, 14].include?(n % 100) ? :many : :other } } } },
:hu => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } },
:id => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } },
:is => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:it => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:iw => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:ja => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } },
:jv => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } },
:ka => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } },
:km => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } },
:kn => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } },
:ko => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } },
:ku => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:lb => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:ln => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } },
:lt => { :i18n => { :plural => { :keys => [:one, :few, :other], :rule => lambda { |n| n % 10 == 1 && !(11..19).include?(n % 100) ? :one : [2, 3, 4, 5, 6, 7, 8, 9].include?(n % 10) && !(11..19).include?(n % 100) ? :few : :other } } } },
:lv => { :i18n => { :plural => { :keys => [:zero, :one, :other], :rule => lambda { |n| n == 0 ? :zero : n % 10 == 1 && n % 100 != 11 ? :one : :other } } } },
:mg => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } },
:mk => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n % 10 == 1 ? :one : :other } } } },
:ml => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:mn => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:mo => { :i18n => { :plural => { :keys => [:one, :few, :other], :rule => lambda { |n| n == 1 ? :one : n == 0 ? :few : :other } } } },
:mr => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:ms => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } },
:mt => { :i18n => { :plural => { :keys => [:one, :few, :many, :other], :rule => lambda { |n| n == 1 ? :one : n == 0 || (2..10).include?(n % 100) ? :few : (11..19).include?(n % 100) ? :many : :other } } } },
:my => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } },
:nah => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:nb => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:ne => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:nl => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:nn => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:no => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:nso => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } },
:oc => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:om => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:or => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:pa => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:pap => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:pl => { :i18n => { :plural => { :keys => [:one, :few, :many, :other], :rule => lambda { |n| n == 1 ? :one : [2, 3, 4].include?(n % 10) && ![12, 13, 14].include?(n % 100) ? :few : (n != 1 && [0, 1].include?(n % 10)) || [5, 6, 7, 8, 9].include?(n % 10) || [12, 13, 14].include?(n % 100) ? :many : :other } } } },
:ps => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:pt => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } },
:"pt-PT" => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:ro => { :i18n => { :plural => { :keys => [:one, :few, :other], :rule => lambda { |n| n == 1 ? :one : n == 0 ? :few : :other } } } },
:ru => { :i18n => { :plural => { :keys => [:one, :few, :many, :other], :rule => lambda { |n| n % 10 == 1 && n % 100 != 11 ? :one : [2, 3, 4].include?(n % 10) && ![12, 13, 14].include?(n % 100) ? :few : n % 10 == 0 || [5, 6, 7, 8, 9].include?(n % 10) || [11, 12, 13, 14].include?(n % 100) ? :many : :other } } } },
:se => { :i18n => { :plural => { :keys => [:one, :two, :other], :rule => lambda { |n| n == 1 ? :one : n == 2 ? :two : :other } } } },
:sh => { :i18n => { :plural => { :keys => [:one, :few, :many, :other], :rule => lambda { |n| n % 10 == 1 && n % 100 != 11 ? :one : [2, 3, 4].include?(n % 10) && ![12, 13, 14].include?(n % 100) ? :few : n % 10 == 0 || [5, 6, 7, 8, 9].include?(n % 10) || [11, 12, 13, 14].include?(n % 100) ? :many : :other } } } },
:sk => { :i18n => { :plural => { :keys => [:one, :few, :other], :rule => lambda { |n| n == 1 ? :one : [2, 3, 4].include?(n) ? :few : :other } } } },
:sl => { :i18n => { :plural => { :keys => [:one, :two, :few, :other], :rule => lambda { |n| n % 100 == 1 ? :one : n % 100 == 2 ? :two : [3, 4].include?(n % 100) ? :few : :other } } } },
:sma => { :i18n => { :plural => { :keys => [:one, :two, :other], :rule => lambda { |n| n == 1 ? :one : n == 2 ? :two : :other } } } },
:smi => { :i18n => { :plural => { :keys => [:one, :two, :other], :rule => lambda { |n| n == 1 ? :one : n == 2 ? :two : :other } } } },
:smj => { :i18n => { :plural => { :keys => [:one, :two, :other], :rule => lambda { |n| n == 1 ? :one : n == 2 ? :two : :other } } } },
:smn => { :i18n => { :plural => { :keys => [:one, :two, :other], :rule => lambda { |n| n == 1 ? :one : n == 2 ? :two : :other } } } },
:sms => { :i18n => { :plural => { :keys => [:one, :two, :other], :rule => lambda { |n| n == 1 ? :one : n == 2 ? :two : :other } } } },
:so => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:sq => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:sr => { :i18n => { :plural => { :keys => [:one, :few, :many, :other], :rule => lambda { |n| n % 10 == 1 && n % 100 != 11 ? :one : [2, 3, 4].include?(n % 10) && ![12, 13, 14].include?(n % 100) ? :few : n % 10 == 0 || [5, 6, 7, 8, 9].include?(n % 10) || [11, 12, 13, 14].include?(n % 100) ? :many : :other } } } },
:sv => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:sw => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:ta => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:te => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:th => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } },
:ti => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } },
:tk => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:tl => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } },
:to => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } },
:tr => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } },
:uk => { :i18n => { :plural => { :keys => [:one, :few, :many, :other], :rule => lambda { |n| n % 10 == 1 && n % 100 != 11 ? :one : [2, 3, 4].include?(n % 10) && ![12, 13, 14].include?(n % 100) ? :few : n % 10 == 0 || [5, 6, 7, 8, 9].include?(n % 10) || [11, 12, 13, 14].include?(n % 100) ? :many : :other } } } },
:ur => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } },
:vi => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } },
:wa => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| [0, 1].include?(n) ? :one : :other } } } },
:yo => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } },
:zh => { :i18n => { :plural => { :keys => [:other], :rule => lambda { |n| :other } } } },
:zu => { :i18n => { :plural => { :keys => [:one, :other], :rule => lambda { |n| n == 1 ? :one : :other } } } }
}
i18n-1.14.7/test/test_helper.rb 0000664 0000000 0000000 00000002435 14743300461 0016213 0 ustar 00root root 0000000 0000000 require 'minitest/autorun'
require 'bundler/setup'
require 'i18n'
require 'mocha/minitest'
require 'test_declarative'
class I18n::TestCase < Minitest::Test
def assert_nothing_raised(*args)
yield
end
def self.key_value?
defined?(ActiveSupport)
end
def setup
super
I18n.load_path = nil
I18n.enforce_available_locales = false
end
def teardown
I18n.locale = nil
I18n.default_locale = nil
I18n.load_path = nil
I18n.available_locales = nil
I18n.backend = nil
I18n.default_separator = nil
I18n.enforce_available_locales = true
I18n.fallbacks = nil if I18n.respond_to?(:fallbacks=)
super
end
protected
def translations
I18n.backend.instance_variable_get(:@translations)
end
def store_translations(locale, data, options = I18n::EMPTY_HASH)
I18n.backend.store_translations(locale, data, options)
end
def locales_dir
File.dirname(__FILE__) + '/test_data/locales'
end
def stub_const(klass, constant, new_value)
old_value = klass.const_get(constant)
klass.send(:remove_const, constant)
klass.const_set(constant, new_value)
yield
ensure
klass.send(:remove_const, constant)
klass.const_set(constant, old_value)
end
end
class DummyRackApp
def call(env)
I18n.locale = :es
end
end
i18n-1.14.7/test/utils_test.rb 0000664 0000000 0000000 00000001652 14743300461 0016074 0 ustar 00root root 0000000 0000000 require 'test_helper'
class I18nUtilsTest < I18n::TestCase
test ".deep_symbolize_keys" do
hash = { 'foo' => { 'bar' => { 'baz' => 'bar' } } }
expected = { :foo => { :bar => { :baz => 'bar' } } }
assert_equal expected, I18n::Utils.deep_symbolize_keys(hash)
end
test "#deep_symbolize_keys with numeric keys" do
hash = { 1 => { 2 => { 3 => 'bar' } } }
expected = { 1 => { 2 => { 3 => 'bar' } } }
assert_equal expected, I18n::Utils.deep_symbolize_keys(hash)
end
test "#except" do
hash = { :foo => 'bar', :baz => 'bar' }
expected = { :foo => 'bar' }
assert_equal expected, I18n::Utils.except(hash, :baz)
end
test "#deep_merge!" do
hash = { :foo => { :bar => { :baz => 'bar' } }, :baz => 'bar' }
I18n::Utils.deep_merge!(hash, :foo => { :bar => { :baz => 'foo' } })
expected = { :foo => { :bar => { :baz => 'foo' } }, :baz => 'bar' }
assert_equal expected, hash
end
end