Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
6.7 KB
Raw Blame
if ENV["COVERAGE"] == "true"
  require "simplecov"
  SimpleCov.start "rails" do
    enable_coverage :branch
  end
end

require_relative "../config/environment"

ENV["RAILS_ENV"] ||= "test"

# Set Plaid to sandbox mode for tests
ENV["PLAID_ENV"] = "sandbox"
ENV["PLAID_CLIENT_ID"] ||= "test_client_id"
ENV["PLAID_SECRET"] ||= "test_secret"

# Fixes Segfaults on M1 Macs when running tests in parallel (temporary workaround)
ENV["PGGSSENCMODE"] = "disable"

require "rails/test_help"
require "minitest/mock"
require "minitest/autorun"
require "mocha/minitest"
require "aasm/minitest"
require "webmock/minitest"
require "rack/test"
require "tempfile"
require "uri"
require Rails.root.join("test/support/sql_query_capture").to_s
require Rails.root.join("test/support/rake_task_test_helper").to_s
require Rails.root.join("test/support/family_lock_test_helper").to_s
require Rails.root.join("test/support/secret_key_base_rotation_helper").to_s
require Rails.root.join("test/support/ai_test_helper").to_s
require Rails.root.join("test/support/ai_legacy_setups").to_s

VCR.configure do |config|
  config.cassette_library_dir = "test/vcr_cassettes"
  config.hook_into :webmock
  config.ignore_localhost = true
  config.ignore_request do |request|
    selenium_remote_url = ENV["SELENIUM_REMOTE_URL"]
    next false if selenium_remote_url.blank?

    request_uri = URI(request.uri)
    selenium_uri = URI(selenium_remote_url)

    request_uri.host.present? &&
      selenium_uri.host.present? &&
      request_uri.host == selenium_uri.host &&
      request_uri.port == selenium_uri.port
  rescue URI::InvalidURIError
    false
  end
  config.default_cassette_options = { erb: true }
  config.filter_sensitive_data("<OPENAI_ACCESS_TOKEN>") { ENV["OPENAI_ACCESS_TOKEN"] }
  config.filter_sensitive_data("<OPENAI_ORGANIZATION_ID>") { ENV["OPENAI_ORGANIZATION_ID"] }
  config.filter_sensitive_data("<STRIPE_SECRET_KEY>") { ENV["STRIPE_SECRET_KEY"] }
  config.filter_sensitive_data("<STRIPE_WEBHOOK_SECRET>") { ENV["STRIPE_WEBHOOK_SECRET"] }
  config.filter_sensitive_data("<PLAID_CLIENT_ID>") { ENV["PLAID_CLIENT_ID"] }
  config.filter_sensitive_data("<PLAID_SECRET>") { ENV["PLAID_SECRET"] }
end

# Configure OmniAuth for testing
OmniAuth.config.test_mode = true
# Allow both GET and POST for OIDC callbacks in tests
OmniAuth.config.allowed_request_methods = [ :get, :post ]

module ActiveSupport
  class TestCase
    # Run tests in parallel with specified workers
    parallelize(workers: :number_of_processors) unless ENV["DISABLE_PARALLELIZATION"] == "true"

    # https://github.com/simplecov-ruby/simplecov/issues/718#issuecomment-538201587
    if ENV["COVERAGE"] == "true"
      parallelize_setup do |worker|
        SimpleCov.command_name "#{SimpleCov.command_name}-#{worker}"
      end

      parallelize_teardown do |worker|
        SimpleCov.result
      end
    end

    # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
    fixtures :all

    # rails-settings-cached keeps an in-memory cache that survives the per-test
    # transaction rollback, so a Setting.* value written in one test leaks into
    # later tests and causes order-dependent failures (e.g. Settings::Hostings
    # reading a stale "" where nil is expected). Reset the cache before every
    # test so each starts from the rolled-back DB state.
    setup { Setting.clear_cache }

    include SqlQueryCapture
    include AiTestHelper

    # Add more helper methods to be used by all tests here...
    def sign_in(user)
      post sessions_path, params: { email: user.email, password: user_password_test }
      Current.session = user.sessions.order(:created_at).last
    end

    def ensure_tailwind_build
      tailwind_build = Rails.root.join("app/assets/builds/tailwind.css")
      FileUtils.mkdir_p(tailwind_build.dirname)
      File.write(tailwind_build, "/* test */") unless tailwind_build.exist?
    end

    def with_env_overrides(overrides = {}, &block)
      ClimateControl.modify(**overrides, &block)
    end

    # Self-hosted mode makes ApplicationController run SelfHostable's
    # `verify_self_host_config` prepended before_action, which pings Redis and
    # redirects to the Redis configuration error page when it can't connect.
    # That check is an infrastructure concern, not what the ~100 callers of this
    # helper are testing, and it depends on REDIS_URL being set and the service
    # being reachable (Redis.new falls back to localhost:6379 otherwise, which
    # is not where Redis runs in the devcontainer or docker compose). Stub the
    # ping so self-hosting tests exercise the controller under test instead of
    # the developer's Redis setup. Tests that care about a Redis outage stub
    # `redis_connected?` to false themselves.
    def with_self_hosting(redis_connected: true)
      Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)
      ApplicationController.any_instance.stubs(:redis_connected?).returns(redis_connected)
      yield
    end

    def api_headers(api_key)
      { "X-Api-Key" => api_key.plain_key }
    end

    def user_password_test
      "maybetestpassword817983172"
    end

    # Writes the email column directly, bypassing encryption, to simulate a
    # row stored before encryption was active and not yet backfilled.
    def store_legacy_plaintext_email(user, email = user.email)
      ActiveRecord::Base.connection.execute(
        ActiveRecord::Base.sanitize_sql([ "UPDATE users SET email = ? WHERE id = ?", email, user.id ])
      )
      email
    end

    def uploaded_file(filename:, content_type:, content: "date,amount\n2024-01-01,1\n")
      tempfile = Tempfile.new([ File.basename(filename, ".*"), File.extname(filename) ])
      tempfile.binmode
      tempfile.write(content)
      tempfile.rewind

      Rack::Test::UploadedFile.new(tempfile.path, content_type, true, original_filename: filename)
    end

    def family_guest
      @family_guest ||= users(:family_admin).family.users.create!(
        first_name: "Readonly",
        last_name: "Guest",
        email: "[email protected]",
        password: user_password_test,
        role: "guest",
        onboarded_at: Time.current,
        ui_layout: "dashboard"
      )
    end

    # Ensures the Investment Contributions category exists for a family
    # Used in transfer tests where this bootstrapped category is required
    # Uses family locale to ensure consistent naming
    def ensure_investment_contributions_category(family)
      I18n.with_locale(family.locale) do
        family.categories.find_or_create_by!(name: Category.investment_contributions_name) do |c|
          c.color = "#0d9488"
          c.lucide_icon = "trending-up"
        end
      end
    end
  end
end

Dir[Rails.root.join("test", "interfaces", "**", "*.rb")].each { |f| require f }