The personal finance app for everyone (by everyone)
Ruby
require "test_helper"
require "i18n/tasks"
require "pathname"
require "yaml"
# We're currently skipping some i18n tests to speed up development. Eventually, we'll make a dedicated
# project for getting i18n working. More details on that here:
# https://github.com/maybe-finance/maybe/issues/1225
class I18nTest < ActiveSupport::TestCase
GERMAN_COVERAGE_GLOBS = [
"config/locales/breadcrumbs/*.yml",
"config/locales/doorkeeper.*.yml",
"config/locales/mailers/**/*.yml",
"config/locales/models/**/*.yml",
"config/locales/views/**/*.yml"
]
def setup
@i18n = I18n::Tasks::BaseTask.new
end
def test_german_locale_files_parse
german_locale_paths.each do |path|
assert_nothing_raised do
YAML.load_file(path, aliases: true)
end
end
end
# The loan chart's labels, cards, table and accessible description all read
# this subtree. Fallbacks would show a German user English rather than a raw
# key, but the rest of UI.account.chart is translated, so a missing subtree
# is a gap and not a choice. Placeholders are compared too: a translation
# that drops %{projected_payoff_date} silently loses the figure it names.
def test_german_loan_chart_keys_and_placeholders_match_english
en = loan_chart_leaves("en")
de = loan_chart_leaves("de")
assert_equal en.keys.sort, de.keys.sort, "UI.account.chart.loan in de.yml must carry every key en.yml does"
en.each do |key, value|
assert_equal value.scan(/%\{\w+\}/).sort, de.fetch(key).to_s.scan(/%\{\w+\}/).sort, "placeholders differ for #{key}"
end
end
# The insights page, the card's "Dig in with AI" button and the push
# notification all read this tree, so a gap shows Spanish users English
# copy, and for the dig-in prompt, an English message in their chat box.
def test_spanish_insights_keys_and_placeholders_match_english
en = view_leaves("insights", "en")
es = view_leaves("insights", "es")
assert_equal en.keys.sort, es.keys.sort, "insights in views/insights/es.yml must carry every key en.yml does"
en.each do |key, value|
assert_equal value.scan(/%\{\w+\}/).sort, es.fetch(key).to_s.scan(/%\{\w+\}/).sort, "placeholders differ for #{key}"
end
end
def test_no_missing_keys
skip "Skipping missing keys test"
missing_keys = @i18n.missing_keys(locales: [ :en ])
assert_empty missing_keys,
"Missing #{missing_keys.leaves.count} i18n keys, run `i18n-tasks missing' to show them"
end
def test_no_unused_keys
skip "Skipping unused keys test"
unused_keys = @i18n.unused_keys(locales: [ :en ])
assert_empty unused_keys,
"#{unused_keys.leaves.count} unused i18n keys, run `i18n-tasks unused' to show them"
end
def test_files_are_normalized
skip "Skipping file normalization test"
non_normalized = @i18n.non_normalized_paths(locales: [ :en ])
error_message = "The following files need to be normalized:\n" \
"#{non_normalized.map { |path| " #{path}" }.join("\n")}\n" \
"Please run `i18n-tasks normalize' to fix"
assert_empty non_normalized, error_message
end
def test_no_inconsistent_interpolations
skip "Skipping inconsistent interpolations test"
inconsistent_interpolations = @i18n.inconsistent_interpolations(locales: [ :en ])
error_message = "#{inconsistent_interpolations.leaves.count} i18n keys have inconsistent interpolations.\n" \
"Please run `i18n-tasks check-consistent-interpolations' to show them"
assert_empty inconsistent_interpolations, error_message
end
# YAML silently resolves duplicate keys by letting the last occurrence win,
# so a duplicated key shadows the earlier definition without any warning
# (see #1506 / #1502, where a stale `transactions.merge_duplicate` string
# shadowed — or was shadowed by — the `merge_duplicate.success/failure`
# mapping in several locales). Parse the raw YAML AST so duplicates can't
# sneak back in.
def test_no_duplicate_keys_within_locale_files
offenses = []
Dir[File.expand_path("../config/locales/**/*.yml", __dir__)].sort.each do |file|
Psych.parse_stream(File.read(file), filename: file).children.each do |doc|
offenses.concat(duplicate_key_offenses(doc.root, [], file))
end
end
assert_empty offenses,
"Duplicate keys found in locale files (the last occurrence silently wins):\n" \
"#{offenses.map { |offense| " #{offense}" }.join("\n")}"
end
# Fallbacks would hand a locale without :short_with_year the English
# "%b %d, %Y", month first, so check each locale without them.
def test_short_with_year_date_format_exists_for_each_locale
locales = Dir[File.expand_path("../config/locales/defaults/*.yml", __dir__)].map { |file| File.basename(file, ".yml") }
missing = locales.sort.reject do |locale|
I18n.t("date.formats.short_with_year", locale: locale, fallback: false, default: nil)
end
assert_empty missing, "date.formats.short_with_year is missing for: #{missing.join(", ")}"
end
def test_short_with_year_follows_the_locale
assert_equal "5. Jan 2027", I18n.l(Date.new(2027, 1, 5), format: :short_with_year, locale: :de)
# The abbreviation takes no case suffix: "tammita" and "Urtk" aren't words.
assert_equal "05. tammi 2027", I18n.l(Date.new(2027, 1, 5), format: :short_with_year, locale: :fi)
assert_equal "2027(e)ko Urt 5", I18n.l(Date.new(2027, 1, 5), format: :short_with_year, locale: :eu)
end
# %e pads a single-digit day with a space: " 5. Jan 2027", "Jan 5, 2027".
def test_short_with_year_has_no_padding_space_on_a_single_digit_day
locales = Dir[File.expand_path("../config/locales/defaults/*.yml", __dir__)].map { |file| File.basename(file, ".yml") }
padded = locales.sort.select do |locale|
I18n.l(Date.new(2027, 1, 5), format: :short_with_year, locale: locale).match?(/\A\s|\s\s/)
end
assert_empty padded, "short_with_year pads the day for: #{padded.join(", ")}"
end
# The bills overview's notices card heads with this. Fallbacks would show the
# English "Changes", so check each bills locale file without them.
def test_bills_notices_heading_exists_for_each_bills_locale
locales = Dir[File.expand_path("../config/locales/views/bills/*.yml", __dir__)].map { |file| File.basename(file, ".yml") }
missing = locales.sort.reject do |locale|
I18n.t("bills.index.notices_heading", locale: locale, fallback: false, default: nil)
end
assert_empty missing, "bills.index.notices_heading is missing for: #{missing.join(", ")}"
end
# The Auto Matches date cell adds "N days apart" under the date. Fallbacks
# would show it in English inside an otherwise translated table.
def test_auto_matches_days_apart_exists_for_each_auto_matches_locale
locales = Dir[File.expand_path("../config/locales/views/auto_matches/*.yml", __dir__)].map { |file| File.basename(file, ".yml") }
missing = locales.sort.reject do |locale|
I18n.t("auto_matches.table.days_apart", locale: locale, count: 3, fallback: false, default: nil)
end
assert_empty missing, "auto_matches.table.days_apart is missing for: #{missing.join(", ")}"
end
# The account status speaks wherever the holdings tab is translated.
def test_account_health_status_keys_exist_wherever_the_holdings_tab_is_translated
{
"holdings.index.new_holding" => %w[
accounts.health_status.negative_positions.detail
accounts.health_status.negative_positions.hint
accounts.health_status.negative_positions.link
accounts.health_status.negative_positions.message
accounts.health_status.sync_failed.message
accounts.health_status.sync_hint
accounts.health_status.sync_stale.message
]
}.each do |sibling, keys|
locales = I18n.available_locales.select { |locale| I18n.t(sibling, locale: locale, fallback: false, default: nil) }
assert_includes locales, :de
locales.each do |locale|
missing = keys.reject { |key| I18n.t(key, locale: locale, fallback: false, default: nil) }
assert_empty missing, "#{locale} translates #{sibling} but is missing #{missing.join(", ")}"
end
end
end
# The All bills default status option. Every bills locale must translate it,
# or the default filter falls back to English.
def test_bills_current_bills_label_exists_for_each_bills_locale
locales = Dir[File.expand_path("../config/locales/views/bills/*.yml", __dir__)].map { |file| File.basename(file, ".yml") }
missing = locales.sort.reject do |locale|
I18n.t("bills.all.current_bills", locale: locale, fallback: false, default: nil)
end
assert_empty missing, "bills.all.current_bills is missing for: #{missing.join(", ")}"
end
# The family setting that fills a blank transaction name and the form
# placeholder that explains it. Fallbacks would show English, so each locale
# that translates the neighbouring key must translate these too.
def test_auto_generate_transaction_name_keys_exist_beside_their_siblings
{
"settings.appearances.show.split_grouped_title" => %w[
settings.appearances.show.auto_generate_transaction_names_title
settings.appearances.show.auto_generate_transaction_names_description
],
"transactions.form.description_placeholder" => %w[transactions.form.description_placeholder_optional]
}.each do |sibling, keys|
locales = I18n.available_locales.select { |locale| I18n.t(sibling, locale: locale, fallback: false, default: nil) }
assert_includes locales, :de
locales.each do |locale|
missing = keys.reject { |key| I18n.t(key, locale: locale, fallback: false, default: nil) }
assert_empty missing, "missing in #{locale}: #{missing.join(", ")}"
end
end
end
# A placeholder the English string does not have is never passed by the
# caller, so I18n raises MissingInterpolationArgument and the page or flash
# breaks for Dutch users only. Plural forms always receive %{count}, so the
# Dutch "one" form may use it where English spells out "1".
def test_dutch_strings_use_no_placeholders_english_lacks
english = locale_leaves("en")
extra = locale_leaves("nl").filter_map do |key, value|
next unless value.is_a?(String) && english[key].is_a?(String)
unknown = value.scan(/%\{\w+\}/) - english[key].scan(/%\{\w+\}/)
unknown -= [ "%{count}" ] if key.match?(/\.(zero|one|two|few|many|other)\z/)
"#{key}: #{unknown.uniq.join(", ")}" if unknown.any?
end
assert_empty extra, "nl placeholders missing from en:\n#{extra.join("\n")}"
end
# The depository, investment and loan forms label their subtype select with
# the accountable's attribute name. A missing entry humanizes to "Subtype".
def test_accountable_subtype_labels_are_translated
[ Depository, Investment, Loan ].each do |model|
%i[en de].each do |locale|
key = "activerecord.attributes.#{model.model_name.i18n_key}.subtype"
assert I18n.t(key, locale: locale, fallback: false, default: nil).present?, "#{key} is missing in #{locale}"
end
end
end
def test_trade_republic_activity_labels_exist_for_each_locale
required_labels = %w[
contribution withdrawal interest dividend card_payment cash_withdrawal
card_fee card_refund tax_refund round_up
]
Dir[File.expand_path("../config/locales/views/trade_republic_items/*.yml", __dir__)].sort.each do |file|
locale = File.basename(file, ".yml")
translations = YAML.load_file(file, aliases: true).fetch(locale)
labels = translations.dig("trade_republic_items", "activities", "labels")
assert labels.is_a?(Hash), "#{file} must define trade_republic_items.activities.labels"
assert_empty required_labels - labels.keys,
"#{file} is missing Trade Republic activity labels"
assert translations.dig("trade_republic_items", "trade_republic_item", "data_quality", "pending_trade_details").present?,
"#{file} is missing trade_republic_item.data_quality.pending_trade_details"
end
end
private
# { "months_saved.one" => "...", ... } for UI.account.chart.loan in one locale.
def loan_chart_leaves(locale)
view_leaves("components", locale, "UI", "account", "chart", "loan")
end
# Leaves of config/locales/views/<dir>/<locale>.yml under the given keys.
def view_leaves(dir, locale, *keys)
tree = YAML.load_file(Pathname.pwd.join("config/locales/views/#{dir}/#{locale}.yml"), aliases: true)
.dig(locale, *keys) || {}
flatten_leaves(tree)
end
def locale_leaves(locale)
Dir[Pathname.pwd.join("config/locales/**/*#{locale}.yml")].each_with_object({}) do |path, leaves|
tree = YAML.load_file(path, aliases: true)&.fetch(locale, nil)
leaves.merge!(flatten_leaves(tree)) if tree.is_a?(Hash)
end
end
def flatten_leaves(tree, prefix = nil)
tree.each_with_object({}) do |(key, value), leaves|
path = [ prefix, key ].compact.join(".")
value.is_a?(Hash) ? leaves.merge!(flatten_leaves(value, path)) : leaves[path] = value
end
end
def german_locale_paths
@german_locale_paths ||= locale_paths.select { |path| path.basename.to_s.match?(/(^|[._-])de\.yml\z/) }
end
def locale_paths
@locale_paths ||= GERMAN_COVERAGE_GLOBS.flat_map { |glob| Pathname.pwd.glob(glob) }.uniq
end
def duplicate_key_offenses(node, path, file)
offenses = []
case node
when Psych::Nodes::Mapping
first_definition_lines = {}
node.children.each_slice(2) do |key_node, value_node|
if key_node.is_a?(Psych::Nodes::Scalar)
key_path = path + [ key_node.value ]
if (first_line = first_definition_lines[key_node.value])
offenses << "#{file}:#{key_node.start_line + 1} duplicate key `#{key_path.join(".")}` (first defined on line #{first_line})"
else
first_definition_lines[key_node.value] = key_node.start_line + 1
end
offenses.concat(duplicate_key_offenses(value_node, key_path, file))
else
offenses.concat(duplicate_key_offenses(value_node, path, file))
end
end
when Psych::Nodes::Sequence
node.children.each { |child| offenses.concat(duplicate_key_offenses(child, path, file)) }
end
offenses
end
end