Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Fix demo data reset skipping the demo family it made (#3635)

Anthony4724a36bc8e7
diff --git a/app/models/demo/data_cleaner.rb b/app/models/demo/data_cleaner.rb
index 829411db23..0d898fcfd4 100644
--- a/app/models/demo/data_cleaner.rb
+++ b/app/models/demo/data_cleaner.rb
@@ -6,26 +6,43 @@ class Demo::DataCleaner
ensure_safe_environment!
end
- # Main entry point for destroying all demo data
+ # Main entry point for destroying all demo data.
+ #
+ # All or nothing. Family.destroy_all used to skip any family whose
+ # before_destroy aborted without saying so, and the settings, invite codes
+ # and exchange rates after it were wiped regardless. The half-cleared
+ # database then crashed on Security.destroy_all (trades still pointing at
+ # securities), and the generator could not recreate the demo users because
+ # their emails were still taken.
def destroy_everything!
- # Clear SSO audit logs first (they reference users)
- SsoAuditLog.destroy_all
+ ActiveRecord::Base.transaction do
+ # Clear SSO audit logs first (they reference users)
+ SsoAuditLog.destroy_all
- # ApiKey#prevent_demo_monitoring_key_destroy! throws :abort to stop the demo
- # monitoring key being revoked from the UI. That abort silently no-ops the
- # entire Family.destroy_all cascade below (accounts/entries/trades all
- # survive), which only then surfaces as a NOT NULL crash in
- # `Security.destroy_all`. Safe to bypass here: this class only runs in
- # dev/test (see #ensure_safe_environment!).
+ # Rows whose foreign key blocks the cascade below and that no
+ # association removes: unlinked provider merchants (DataCleanerJob only
+ # drops them after 30 days) and the request logs of impersonation
+ # sessions.
+ FamilyMerchantAssociation.delete_all
+ ImpersonationSessionLog.delete_all
- ApiKey.where(display_key: ApiKey::DEMO_MONITORING_KEY).delete_all
+ disarm_destroy_guards!
- Family.destroy_all
- Setting.destroy_all
- InviteCode.destroy_all
- ExchangeRate.destroy_all
- Security.destroy_all
- Security::Price.destroy_all
+ Family.find_each do |family|
+ family.destroy!
+ rescue ActiveRecord::RecordNotDestroyed => e
+ # Name the guard, not just the record: "Failed to destroy User" alone
+ # does not say which callback aborted.
+ reasons = e.record&.errors&.full_messages&.to_sentence.presence || "a before_destroy callback aborted"
+ raise ActiveRecord::RecordNotDestroyed.new("#{e.message} (#{reasons})", e.record)
+ end
+
+ Setting.destroy_all
+ InviteCode.destroy_all
+ ExchangeRate.destroy_all
+ Security.destroy_all
+ Security::Price.destroy_all
+ end
puts "Data cleared"
end
@@ -37,4 +54,23 @@ class Demo::DataCleaner
raise SecurityError, "Demo::DataCleaner can only be used in #{SAFE_ENVIRONMENTS.join(', ')} environments. Current: #{Rails.env}"
end
end
+
+ # Guards that protect real data from the UI and have nothing to protect
+ # here. Each one aborts the destroy of a record the reset must remove.
+ # Safe to bypass: this class only runs in dev/test (see
+ # #ensure_safe_environment!).
+ def disarm_destroy_guards!
+ # ApiKey#prevent_demo_monitoring_key_destroy! stops the demo monitoring
+ # key being revoked from the UI.
+ ApiKey.where(display_key: ApiKey::DEMO_MONITORING_KEY).delete_all
+
+ # A family cancels its Stripe subscription before it goes, and aborts
+ # when Stripe refuses. The demo family's is fake ("sub_demo_123"), so the
+ # cancel always fails, and a dev reset must not cancel a real one either.
+ Subscription.where.not(status: %w[canceled incomplete_expired]).update_all(status: "canceled")
+
+ # The last active super admin cannot be deleted, and a reset deletes
+ # every user.
+ User.where(role: "super_admin").update_all(role: "admin")
+ end
end
diff --git a/test/models/demo/data_cleaner_test.rb b/test/models/demo/data_cleaner_test.rb
new file mode 100644
index 0000000000..f5e5405a2d
--- /dev/null
+++ b/test/models/demo/data_cleaner_test.rb
@@ -0,0 +1,94 @@
+require "test_helper"
+
+class Demo::DataCleanerTest < ActiveSupport::TestCase
+ setup do
+ # Fixture families hold Plaid items, and destroying one asks Plaid to
+ # remove it. That call is not what these tests are about.
+ Provider::Registry.stubs(:plaid_provider_for_region).returns(nil)
+ end
+
+ # The generator gives its demo family a fake Stripe subscription, and a
+ # family cancels its subscription at Stripe before it goes. The cancel always
+ # failed, so `rake demo_data:default SKIP_CLEAR=0` could never remove the
+ # demo family it had created itself.
+ test "clears a family with a Stripe subscription without calling Stripe" do
+ family = Family.create!(name: "Demo Family")
+ family.start_subscription!("sub_demo_123")
+ Provider::Registry.expects(:get_provider).with(:stripe).never
+
+ clear!
+
+ assert_equal 0, Family.count
+ assert_equal 0, Subscription.count
+ end
+
+ test "clears the last active super admin" do
+ admin = users(:family_admin)
+ User.where(role: "super_admin").where.not(id: admin.id).update_all(role: "admin")
+ admin.update_columns(role: "super_admin", active: true)
+
+ clear!
+
+ assert_equal 0, User.count
+ end
+
+ # Neither row has an association that removes it, and each one's foreign key
+ # stopped the cascade at the family or user it points to.
+ test "clears families that unlinked a merchant or were impersonated" do
+ FamilyMerchantAssociation.create!(family: families(:dylan_family), merchant: merchants(:netflix),
+ unlinked_at: 1.day.ago)
+ impersonation_sessions(:in_progress).logs.create!(controller: "pages", action: "dashboard",
+ method: "GET", path: "/")
+
+ clear!
+
+ assert_equal 0, Family.count
+ assert_equal 0, ImpersonationSessionLog.count
+ end
+
+ # Family.destroy_all skipped a family whose destroy aborted without a word,
+ # then wiped the settings, invite codes and exchange rates anyway.
+ test "a family that cannot be destroyed stops the reset before anything else goes" do
+ Setting.exchange_rate_provider = "yahoo_finance"
+ families = Family.count
+ exchange_rates = ExchangeRate.count
+ assert exchange_rates.positive?, "the fixtures carry exchange rates for this check"
+
+ Family.any_instance.stubs(:destroy!).raises(ActiveRecord::RecordNotDestroyed.new("Failed to destroy Family"))
+
+ assert_raises(ActiveRecord::RecordNotDestroyed) { clear! }
+
+ assert_equal families, Family.count
+ assert_equal exchange_rates, ExchangeRate.count
+ assert_equal "yahoo_finance", Setting.exchange_rate_provider
+ end
+
+ # The guards are disarmed before any family goes. A reset that fails after
+ # that must not leave subscriptions cancelled and the super admin demoted.
+ test "a failed reset rolls back what it already did" do
+ subscription = subscriptions(:active)
+ super_admin = User.find_by!(role: "super_admin")
+ Family.any_instance.stubs(:destroy!).raises(ActiveRecord::RecordNotDestroyed.new("Failed to destroy Family"))
+
+ assert_raises(ActiveRecord::RecordNotDestroyed) { clear! }
+
+ assert_equal "active", subscription.reload.status
+ assert_equal "super_admin", super_admin.reload.role
+ end
+
+ test "a failed destroy names the guard that aborted it" do
+ user = users(:family_admin)
+ user.errors.add(:base, "cannot remove the last super admin")
+ Family.any_instance.stubs(:destroy!).raises(ActiveRecord::RecordNotDestroyed.new("Failed to destroy User", user))
+
+ error = assert_raises(ActiveRecord::RecordNotDestroyed) { clear! }
+
+ assert_includes error.message, "cannot remove the last super admin"
+ assert_equal user, error.record
+ end
+
+ private
+ def clear!
+ capture_io { Demo::DataCleaner.new.destroy_everything! }
+ end
+end