The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Use with-dynamic-fn-redefs for re-exported test redefs (#83459)
Chris Truter40559c1e70e4
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_config/file/databases_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_config/file/databases_test.cljindex 7dc08ae1f3b..97941ae8fb5 100644--- a/enterprise/backend/test/metabase_enterprise/advanced_config/file/databases_test.clj+++ b/enterprise/backend/test/metabase_enterprise/advanced_config/file/databases_test.clj@@ -191,12 +191,12 @@extract-calls (atom 0)](delete-existing!)(try- (with-redefs [sample-data/extract-and-sync-sample-database!- (fn []- (swap! extract-calls inc)- ;; simulate extract by inserting a sample row- (t2/insert! :model/Database- {:name "Sample Database" :engine :h2 :details {} :is_sample true}))]+ (mt/with-dynamic-fn-redefs [sample-data/extract-and-sync-sample-database!+ (fn []+ (swap! extract-calls inc)+ ;; simulate extract by inserting a sample row+ (t2/insert! :model/Database+ {:name "Sample Database" :engine :h2 :details {} :is_sample true}))](is (= :ok(advanced-config.file/initialize!{:version 1@@ -218,8 +218,8 @@:engine :h2:details {:db "preexisting"}:is_sample true}]- (with-redefs [sample-data/extract-and-sync-sample-database!- (fn [] (swap! extract-calls inc))]+ (mt/with-dynamic-fn-redefs [sample-data/extract-and-sync-sample-database!+ (fn [] (swap! extract-calls inc))](is (= :ok(advanced-config.file/initialize!{:version 1diff --git a/enterprise/backend/test/metabase_enterprise/advanced_config/file/users_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_config/file/users_test.cljindex 2d74ebaff63..dd130cf4332 100644--- a/enterprise/backend/test/metabase_enterprise/advanced_config/file/users_test.clj+++ b/enterprise/backend/test/metabase_enterprise/advanced_config/file/users_test.clj@@ -72,7 +72,7 @@(testing "If this is the first user being created, always make the user a superuser regardless of what is specified"(try(testing "Create the first User"- (with-redefs [setup/has-user-setup (constantly false)]+ (mt/with-dynamic-fn-redefs [setup/has-user-setup (constantly false)](is (= :ok(advanced-config.file/initialize!{:version 1diff --git a/enterprise/backend/test/metabase_enterprise/audit_app/audit_test.clj b/enterprise/backend/test/metabase_enterprise/audit_app/audit_test.cljindex 096e8505c8b..1f228e70313 100644--- a/enterprise/backend/test/metabase_enterprise/audit_app/audit_test.clj+++ b/enterprise/backend/test/metabase_enterprise/audit_app/audit_test.clj@@ -465,15 +465,15 @@(with-audit-db-restoration!(let [audit-db (t2/select-one :model/Database :is_audit true)];; "Boot 1": steady state (checksums current), the engine-changed sync dies mid-flight.- (with-redefs [sync.core/sync-database! (fn [& _] (throw (ex-info "killed mid-sync" {})))]+ (mt/with-dynamic-fn-redefs [sync.core/sync-database! (fn [& _] (throw (ex-info "killed mid-sync" {})))](#'ee-audit/maybe-sync-audit-db! audit-db true));; "Boot 2": the full, un-stubbed pipeline, spying on audit-DB syncs.(let [audit-db-syncs (atom 0)- real-sync sync.core/sync-database!]- (with-redefs [sync.core/sync-database! (fn [db & [opts]]- (when (:is_audit db)- (swap! audit-db-syncs inc))- (real-sync db opts))]+ real-sync (mt/original-fn #'sync.core/sync-database!)]+ (mt/with-dynamic-fn-redefs [sync.core/sync-database! (fn [db & [opts]]+ (when (:is_audit db)+ (swap! audit-db-syncs inc))+ (real-sync db opts))](mbc/ensure-audit-db-installed!))(testing "the boot after an interrupted engine-changed sync re-syncs the audit DB"(is (pos? @audit-db-syncs)))))))diff --git a/enterprise/backend/test/metabase_enterprise/audit_app/task/truncate_audit_tables_test.clj b/enterprise/backend/test/metabase_enterprise/audit_app/task/truncate_audit_tables_test.cljindex b76d5899d59..fbb5f1569f3 100644--- a/enterprise/backend/test/metabase_enterprise/audit_app/task/truncate_audit_tables_test.clj+++ b/enterprise/backend/test/metabase_enterprise/audit_app/task/truncate_audit_tables_test.clj@@ -39,7 +39,7 @@(is (= #{qe1-id qe2-id qe3-id}(t2/select-fn-set :id :model/QueryExecution {:where [:in :id [qe1-id qe2-id qe3-id]]}))));; Mock a cloud environment so that we can change the setting value via env var- (with-redefs [premium-features/is-hosted? (constantly true)]+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly true)](testing "When the threshold is 0 (representing infinity), no rows are deleted"(mt/with-temp-env-var-value! [mb-audit-max-retention-days 0](#'task.truncate-audit-tables/truncate-audit-tables!)@@ -61,7 +61,7 @@:model/AuditLog {al3-id :id} (merge (audit-log-defaults){:timestamp (t/minus (t/offset-date-time) (t/years 1))})];; Mock a cloud environment so that we can change the setting value via env var- (with-redefs [premium-features/is-hosted? (constantly true)]+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly true)](testing "When the threshold is 30 days, two rows are deleted"(mt/with-temp-env-var-value! [mb-audit-max-retention-days 30](#'task.truncate-audit-tables/truncate-audit-tables!)@@ -84,7 +84,7 @@:model/ViewLog {vl3-id :id} (merge (view-log-defaults){:timestamp (t/minus (t/offset-date-time) (t/years 1))})];; Mock a cloud environment so that we can change the setting value via env var- (with-redefs [premium-features/is-hosted? (constantly true)]+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly true)](testing "When the threshold is 30 days, two rows are deleted"(mt/with-temp-env-var-value! [mb-audit-max-retention-days 30](#'task.truncate-audit-tables/truncate-audit-tables!)diff --git a/enterprise/backend/test/metabase_enterprise/cloud_add_ons/api_test.clj b/enterprise/backend/test/metabase_enterprise/cloud_add_ons/api_test.cljindex 1ba984696de..3149114e9f7 100644--- a/enterprise/backend/test/metabase_enterprise/cloud_add_ons/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/cloud_add_ons/api_test.clj@@ -56,9 +56,9 @@{:terms_of_service true})))))(testing "succeeds"(let [{store-api-proxy :proxy store-api-calls :calls} (semantic.tu/spy (constantly nil))- {clear-token-cache-proxy :proxy clear-token-cache-calls :calls} (semantic.tu/spy premium-features/clear-cache!)]- (with-redefs [hm.client/call store-api-proxy- premium-features/clear-cache! clear-token-cache-proxy]+ {clear-token-cache-proxy :proxy clear-token-cache-calls :calls} (semantic.tu/spy (mt/original-fn #'premium-features/clear-cache!))]+ (mt/with-dynamic-fn-redefs [hm.client/call store-api-proxy+ premium-features/clear-cache! clear-token-cache-proxy](is (=? {}(mt/user-http-request :crowberto :post 200 "ee/cloud-add-ons/metabase-ai"{:terms_of_service true})))@@ -118,9 +118,9 @@(testing "succeeds, provisioning dwh-rent and etl-connections together"(mt/with-premium-features #{:hosting :audit-app}(let [{store-api-proxy :proxy store-api-calls :calls} (semantic.tu/spy (constantly nil))- {clear-token-cache-proxy :proxy clear-token-cache-calls :calls} (semantic.tu/spy premium-features/clear-cache!)]- (with-redefs [hm.client/call store-api-proxy- premium-features/clear-cache! clear-token-cache-proxy]+ {clear-token-cache-proxy :proxy clear-token-cache-calls :calls} (semantic.tu/spy (mt/original-fn #'premium-features/clear-cache!))]+ (mt/with-dynamic-fn-redefs [hm.client/call store-api-proxy+ premium-features/clear-cache! clear-token-cache-proxy](is (=? {}(mt/user-http-request :crowberto :post 200 "ee/cloud-add-ons/dwh-rent" {})))(is (= [{:args [:change-add-ons@@ -179,9 +179,9 @@(mt/user-http-request :crowberto :delete 500 "ee/cloud-add-ons/metabase-ai-managed")))))(testing "succeeds"(let [{store-api-proxy :proxy store-api-calls :calls} (semantic.tu/spy (constantly nil))- {clear-token-cache-proxy :proxy clear-token-cache-calls :calls} (semantic.tu/spy premium-features/clear-cache!)]- (with-redefs [hm.client/call store-api-proxy- premium-features/clear-cache! clear-token-cache-proxy]+ {clear-token-cache-proxy :proxy clear-token-cache-calls :calls} (semantic.tu/spy (mt/original-fn #'premium-features/clear-cache!))]+ (mt/with-dynamic-fn-redefs [hm.client/call store-api-proxy+ premium-features/clear-cache! clear-token-cache-proxy](is (=? {}(mt/user-http-request :crowberto :delete 200 "ee/cloud-add-ons/metabase-ai-managed")))(is (= [{:args [:change-add-ons@@ -205,9 +205,9 @@(testing "succeeds, removing dwh-rent and etl-connections together"(mt/with-premium-features #{:hosting}(let [{store-api-proxy :proxy store-api-calls :calls} (semantic.tu/spy (constantly nil))- {clear-token-cache-proxy :proxy clear-token-cache-calls :calls} (semantic.tu/spy premium-features/clear-cache!)]- (with-redefs [hm.client/call store-api-proxy- premium-features/clear-cache! clear-token-cache-proxy]+ {clear-token-cache-proxy :proxy clear-token-cache-calls :calls} (semantic.tu/spy (mt/original-fn #'premium-features/clear-cache!))]+ (mt/with-dynamic-fn-redefs [hm.client/call store-api-proxy+ premium-features/clear-cache! clear-token-cache-proxy](is (=? {}(mt/user-http-request :crowberto :delete 200 "ee/cloud-add-ons/dwh-rent")))(is (= [{:args [:change-add-onsdiff --git a/enterprise/backend/test/metabase_enterprise/dependencies/task/backfill_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/task/backfill_test.cljindex 5fc75181057..58deb44af0f 100644--- a/enterprise/backend/test/metabase_enterprise/dependencies/task/backfill_test.clj+++ b/enterprise/backend/test/metabase_enterprise/dependencies/task/backfill_test.clj@@ -485,7 +485,7 @@(reset! scheduled [])(thunk)(count @scheduled))]- (with-redefs [task/schedule-task! (fn [& args] (swap! scheduled conj args) nil)]+ (mt/with-dynamic-fn-redefs [task/schedule-task! (fn [& args] (swap! scheduled conj args) nil)](with-redefs [env/env (assoc env/env :mb-dependency-backfill-batch-size "0")](testing "the 1-second event-driven trigger is suppressed"(is (zero? (scheduled-by dependencies.backfill/trigger-backfill-job!))))@@ -565,7 +565,7 @@:terminal false :next_retry_at [:not= nil])"test setup: the card must be in retry backoff")(let [actionable? (fn [licence]- (with-redefs [premium-features/canonically-has-feature? (constantly licence)]+ (mt/with-dynamic-fn-redefs [premium-features/canonically-has-feature? (constantly licence)](#'dependencies.backfill/has-pending-retries?)))](testing "licensed: the pending retry keeps the job scheduled"(is (true? (actionable? true))))@@ -600,9 +600,9 @@task/init! recovers on boot, but survivable Errors -- StackOverflowError from deeply nested SQL, anAssertionError, a LinkageError -- leave a live process with a dead job."(let [scheduled (atom [])]- (with-redefs [task/schedule-task! (fn [& args] (swap! scheduled conj args) nil)- dependencies.backfill/backfill-dependencies!- (fn [& _] (throw (Error. "simulated fatal error")))]+ (mt/with-dynamic-fn-redefs [task/schedule-task! (fn [& args] (swap! scheduled conj args) nil)+ dependencies.backfill/backfill-dependencies!+ (fn [& _] (throw (Error. "simulated fatal error")))](testing "the Error still propagates"(is (thrown-with-msg? Error #"simulated fatal error"(#'dependencies.backfill/run-and-reschedule! nil))))diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/task/entity_check_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/task/entity_check_test.cljindex 9ac1057c497..a7c89c87e99 100644--- a/enterprise/backend/test/metabase_enterprise/dependencies/task/entity_check_test.clj+++ b/enterprise/backend/test/metabase_enterprise/dependencies/task/entity_check_test.clj@@ -22,14 +22,14 @@(reset! scheduled [])(thunk)(count @scheduled))]- (with-redefs [task/schedule-task! (fn [& args] (swap! scheduled conj args) nil)]+ (mt/with-dynamic-fn-redefs [task/schedule-task! (fn [& args] (swap! scheduled conj args) nil)](with-redefs [env/env (assoc env/env :mb-dependency-entity-check-batch-size "0")](testing "the 1-second event-driven trigger is suppressed"(is (zero? (scheduled-by dependencies.entity-check/trigger-entity-check-job!))))(testing "but task/init! still puts the job on its periodic schedule"(is (= 1 (scheduled-by #(task/init! ::dependencies.entity-check/DependencyEntityCheck)))))(testing "and a run keeps the periodic chain going"- (with-redefs [premium-features/canonically-has-feature? (constantly true)]+ (mt/with-dynamic-fn-redefs [premium-features/canonically-has-feature? (constantly true)](is (= 1 (scheduled-by #(#'dependencies.entity-check/reschedule-after-run! nil)))))))(testing "a positive batch size schedules from the event trigger too"(with-redefs [env/env (assoc env/env :mb-dependency-entity-check-batch-size "5")]@@ -47,10 +47,10 @@(let [scheduled (atom [])scheduled-by (fn [licence](reset! scheduled [])- (with-redefs [premium-features/canonically-has-feature? (constantly licence)]+ (mt/with-dynamic-fn-redefs [premium-features/canonically-has-feature? (constantly licence)](#'dependencies.entity-check/reschedule-after-run! nil))(count @scheduled))]- (with-redefs [task/schedule-task! (fn [& args] (swap! scheduled conj args) nil)]+ (mt/with-dynamic-fn-redefs [task/schedule-task! (fn [& args] (swap! scheduled conj args) nil)](testing "licensed: keeps itself scheduled"(is (= 1 (scheduled-by true))))(testing "indeterminate: keeps the chain alive rather than ending it on a transient failure"@@ -72,7 +72,7 @@came from content-change handlers. Enabling the feature on an idle instance left the periodic checker deaduntil the next process restart."(let [scheduled (atom [])]- (with-redefs [task/schedule-task! (fn [& args] (swap! scheduled conj args) nil)]+ (mt/with-dynamic-fn-redefs [task/schedule-task! (fn [& args] (swap! scheduled conj args) nil)](mt/with-premium-features #{:dependencies}(events/publish-event! :event/set-premium-embedding-token {})(is (contains? (scheduled-job-names @scheduled) entity-check-job-name)))))))diff --git a/enterprise/backend/test/metabase_enterprise/email/api_test.clj b/enterprise/backend/test/metabase_enterprise/email/api_test.cljindex b2171829277..fb11b54c77a 100644--- a/enterprise/backend/test/metabase_enterprise/email/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/email/api_test.clj@@ -27,12 +27,12 @@;; There is a lot of overlap with the /api/email test, but enough differences that we keep them separate.;; NOTE: When adding tests, ask yourself "should this also be tested in the /api/email test?"(testing "PUT /api/ee/email/override - check updating email settings"- (with-redefs [premium-features/is-hosted? (constantly false)]+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly false)](mt/with-premium-features [:cloud-custom-smtp](testing "Cannot call without hosting"(is (= "API is not available on non-hosted servers."(mt/user-http-request :crowberto :put 402 "ee/email/override" default-email-override-settings))))))- (with-redefs [premium-features/is-hosted? (constantly true)]+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly true)](mt/with-premium-features [](testing "Cannot call without the :cloud-custom-smtp feature"(is (= "Custom SMTP is a paid feature not currently available to your instance. Please upgrade to use it. Learn more at metabase.com/upgrade/"@@ -98,12 +98,12 @@(deftest clear-email-override-settings-test(testing "DELETE /api/ee/email/override"- (with-redefs [premium-features/is-hosted? (constantly false)]+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly false)](mt/with-premium-features [:cloud-custom-smtp](testing "Cannot call without hosting"(is (= "API is not available on non-hosted servers."(mt/user-http-request :crowberto :delete 402 "ee/email/override" default-email-override-settings))))))- (with-redefs [premium-features/is-hosted? (constantly true)]+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly true)](mt/with-premium-features [:cloud-custom-smtp](tu/discard-setting-changes [email-smtp-host-override email-smtp-port-override email-smtp-security-overrideemail-smtp-username-override email-smtp-password-override]diff --git a/enterprise/backend/test/metabase_enterprise/embeddings/client_test.clj b/enterprise/backend/test/metabase_enterprise/embeddings/client_test.cljindex aceac2c26d4..d4f2e725a5b 100644--- a/enterprise/backend/test/metabase_enterprise/embeddings/client_test.clj+++ b/enterprise/backend/test/metabase_enterprise/embeddings/client_test.clj@@ -2,16 +2,17 @@(:require[clojure.test :refer :all][metabase-enterprise.embeddings.client :as embeddings.client]- [metabase-enterprise.semantic-search.core :as semantic-search]))+ [metabase-enterprise.semantic-search.core :as semantic-search]+ [metabase.test :as mt]))(set! *warn-on-reflection* true)(deftest legacy-model-dimensions-are-normalized-test(let [captured (atom nil)]- (with-redefs [semantic-search/get-embeddings-batch- (fn [model texts & {:as opts}]- (reset! captured [model texts opts])- [[1.0 2.0]])]+ (mt/with-dynamic-fn-redefs [semantic-search/get-embeddings-batch+ (fn [model texts & {:as opts}]+ (reset! captured [model texts opts])+ [[1.0 2.0]])](is (= [[1.0 2.0]](embeddings.client/get-embeddings-batch{:provider "ai-service" :model-name "model" :model-dimensions 2}@@ -24,10 +25,10 @@(deftest embeds-through-the-connection-keyed-after-the-provider-test(let [captured (atom nil)]- (with-redefs [semantic-search/get-embeddings-batch- (fn [_model _texts & {:as opts}]- (reset! captured opts)- [[1.0 2.0]])]+ (mt/with-dynamic-fn-redefs [semantic-search/get-embeddings-batch+ (fn [_model _texts & {:as opts}]+ (reset! captured opts)+ [[1.0 2.0]])](embeddings.client/get-embeddings-batch {:provider "openai" :model-name "model" :model-dimensions 2} ["text"])(is (= {:connection-key "openai"} @captured)))))diff --git a/enterprise/backend/test/metabase_enterprise/metabot/api_test.clj b/enterprise/backend/test/metabase_enterprise/metabot/api_test.cljindex 597cd1c609c..91698367153 100644--- a/enterprise/backend/test/metabase_enterprise/metabot/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/metabot/api_test.clj@@ -60,9 +60,9 @@(deftest usage-get-returns-token-status-usage-test(mt/with-premium-features #{:metabot-v3}- (with-redefs [premium-features/token-status (constantly {:meters {:anthropic:claude-sonnet-4-6:tokens {:meter-value 12345- :meter-free-units 1337- :meter-updated-at "2026-04-02T19:29:12Z"}}})]+ (mt/with-dynamic-fn-redefs [premium-features/token-status (constantly {:meters {:anthropic:claude-sonnet-4-6:tokens {:meter-value 12345+ :meter-free-units 1337+ :meter-updated-at "2026-04-02T19:29:12Z"}}})](is (= {:tokens 12345:free_tokens 1337:updated_at "2026-04-02T19:29:12Z"diff --git a/enterprise/backend/test/metabase_enterprise/metabot/tools/semantic_search_test.clj b/enterprise/backend/test/metabase_enterprise/metabot/tools/semantic_search_test.cljindex 0f7f54d18a0..e43e51a025b 100644--- a/enterprise/backend/test/metabase_enterprise/metabot/tools/semantic_search_test.clj+++ b/enterprise/backend/test/metabase_enterprise/metabot/tools/semantic_search_test.clj@@ -44,32 +44,32 @@:name "Sales Dashboard":description "Dashboard for sales":verified true}]- (with-redefs [perms/impersonated-user? (fn [] false)- perms/sandboxed-user? (fn [] false)- search.engine/active-engines (constantly [:search.engine/semantic :search.engine/appdb])- ;; The per-query search now runs through ranked-results (each sub-test mocks that).- ;; search-results — the one-time hydrate step — is a passthrough so the mocked ranked- ;; records reach postprocess-search-result unchanged.- search-core/search-results (fn [_ctx _model-set ranked] {:data (vec ranked)})]+ (mt/with-dynamic-fn-redefs [perms/impersonated-user? (fn [] false)+ perms/sandboxed-user? (fn [] false)+ search.engine/active-engines (constantly [:search.engine/semantic :search.engine/appdb])+ ;; The per-query search now runs through ranked-results (each sub-test mocks that).+ ;; search-results — the one-time hydrate step — is a passthrough so the mocked ranked+ ;; records reach postprocess-search-result unchanged.+ search-core/search-results (fn [_ctx _model-set ranked] {:data (vec ranked)})](testing "search returns postprocessed results for term queries"- (with-redefs [search-core/ranked-results (fn [_] [order-table])]+ (mt/with-dynamic-fn-redefs [search-core/ranked-results (fn [_] [order-table])](let [args {:term-queries ["orders"]:entity-types ["table"]}results (search/search args)expected [(#'search/postprocess-search-result order-table)]](is (= expected results)))))(testing "search returns postprocessed results for semantic queries"- (with-redefs [search-core/ranked-results (fn [_] [dashboard])]+ (mt/with-dynamic-fn-redefs [search-core/ranked-results (fn [_] [dashboard])](let [args {:semantic-queries ["sales metrics"]:entity-types ["dashboard"]}results (search/search args)expected [(#'search/postprocess-search-result dashboard)]](is (= expected results)))))(testing "search combines term and semantic queries using RRF"- (with-redefs [search-core/ranked-results (fn [context]- (if (= (:search-string context) "orders")- [order-table]- [dashboard]))]+ (mt/with-dynamic-fn-redefs [search-core/ranked-results (fn [context]+ (if (= (:search-string context) "orders")+ [order-table]+ [dashboard]))](let [args {:term-queries ["orders"]:semantic-queries ["sales"]:entity-types ["table" "dashboard"]}@@ -96,8 +96,8 @@(is (some #(= (:id %) 1) results))(is (some #(= (:id %) 2) results)))))(testing "search applies RRF to overlapping results"- (with-redefs [search-core/ranked-results (fn [_]- [order-table dashboard])]+ (mt/with-dynamic-fn-redefs [search-core/ranked-results (fn [_]+ [order-table dashboard])](let [args {:term-queries ["orders" "sales"]:entity-types ["table" "dashboard"]}results (search/search args)]@@ -106,7 +106,7 @@(is (some #(= (:id %) 1) results))(is (some #(= (:id %) 2) results)))))(testing "search handles empty results"- (with-redefs [search-core/ranked-results (fn [_] [])]+ (mt/with-dynamic-fn-redefs [search-core/ranked-results (fn [_] [])](let [args {:term-queries ["nonexistent"]:entity-types ["table"]}results (search/search args)]@@ -114,13 +114,13 @@(testing "search with metabot verified-or-curated content flag"(let [metabot {:entity_id "test-bot":use_verified_content true}]- (with-redefs [metabot.db/metabot-by-entity-id (fn [entity-id]- (is (= "test-bot" entity-id) "Should look up the Metabot")- metabot)- search-core/ranked-results (fn [context]- ;; use_verified_content now drives the curated filter, not :verified- (is (true? (:curated? context)))- [dashboard])]+ (mt/with-dynamic-fn-redefs [metabot.db/metabot-by-entity-id (fn [entity-id]+ (is (= "test-bot" entity-id) "Should look up the Metabot")+ metabot)+ search-core/ranked-results (fn [context]+ ;; use_verified_content now drives the curated filter, not :verified+ (is (true? (:curated? context)))+ [dashboard])](let [results (search/search {:term-queries ["test"]:metabot-id "test-bot":entity-types ["dashboard"]})]diff --git a/enterprise/backend/test/metabase_enterprise/mfa/ldap_flow_test.clj b/enterprise/backend/test/metabase_enterprise/mfa/ldap_flow_test.cljindex 930f68ed5b2..7aa63130ea6 100644--- a/enterprise/backend/test/metabase_enterprise/mfa/ldap_flow_test.clj+++ b/enterprise/backend/test/metabase_enterprise/mfa/ldap_flow_test.clj@@ -91,7 +91,7 @@:provider "totp":confirmed_at (t/instant):credentials {:secret secret}})- (with-redefs [sso/find-user (fn [& _] (throw (ex-info "connection refused" {})))]+ (mt/with-dynamic-fn-redefs [sso/find-user (fn [& _] (throw (ex-info "connection refused" {})))](testing "enroll re-auth with the directory down is a 400, not a 500"(is (=? {:errors {:password some?}}(mt/client session-key :post 400 "ee/mfa/enroll"diff --git a/enterprise/backend/test/metabase_enterprise/premium_features/airgap_test.clj b/enterprise/backend/test/metabase_enterprise/premium_features/airgap_test.cljindex f5ef62d2e7d..44c5eb02c8a 100644--- a/enterprise/backend/test/metabase_enterprise/premium_features/airgap_test.clj+++ b/enterprise/backend/test/metabase_enterprise/premium_features/airgap_test.clj@@ -4,18 +4,19 @@[clojure.string :as str][clojure.test :refer :all][metabase-enterprise.premium-features.airgap :as airgap]- [metabase.premium-features.core :as premium-features]))+ [metabase.premium-features.core :as premium-features]+ [metabase.test :as mt]))(defn- test-fake-features! [& {:keys [token-fn pubk-fn]}]- (with-redefs- ;; due to the way premium embedding token is implemented, we need to provide a token and a public key,- ;; so we cannot set this with `mt/with-temporary-setting-values`.- [premium-features/premium-embedding-token (constantly (-> (io/resource "fake_ag_token.txt")- slurp- str/trim- ((or token-fn identity))))- airgap/pubkey-reader (fn [] (-> (io/reader (io/resource "fake_pubkey.pem"))- ((or pubk-fn identity))))]+ (mt/with-dynamic-fn-redefs+ ;; due to the way premium embedding token is implemented, we need to provide a token and a public key,+ ;; so we cannot set this with `mt/with-temporary-setting-values`.+ [premium-features/premium-embedding-token (constantly (-> (io/resource "fake_ag_token.txt")+ slurp+ str/trim+ ((or token-fn identity))))+ airgap/pubkey-reader (fn [] (-> (io/reader (io/resource "fake_pubkey.pem"))+ ((or pubk-fn identity))))](#'airgap/decode-token (premium-features/premium-embedding-token))))(deftest ag-token-decryption-testdiff --git a/enterprise/backend/test/metabase_enterprise/replacement/api_test.clj b/enterprise/backend/test/metabase_enterprise/replacement/api_test.cljindex 3d1c9eeccfb..e13d5e4f5a4 100644--- a/enterprise/backend/test/metabase_enterprise/replacement/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/replacement/api_test.clj@@ -428,7 +428,7 @@:type :model:name "Model"}](mt/with-model-cleanup [:model/ReplacementRun :model/Transform]- (with-redefs [transforms/execute! (fn [_ _] (throw (ex-info "Simulated transform failure" {})))]+ (mt/with-dynamic-fn-redefs [transforms/execute! (fn [_ _] (throw (ex-info "Simulated transform failure" {})))](snowplow-test/with-fake-snowplow-collector(let [response (mt/user-http-request :crowberto :post 202"ee/replacement/replace-model-with-transform"diff --git a/enterprise/backend/test/metabase_enterprise/security_center/notification_test.clj b/enterprise/backend/test/metabase_enterprise/security_center/notification_test.cljindex 16976b36065..bf914500e16 100644--- a/enterprise/backend/test/metabase_enterprise/security_center/notification_test.clj+++ b/enterprise/backend/test/metabase_enterprise/security_center/notification_test.clj@@ -459,7 +459,7 @@"Run `thunk` and return the Snowplow `security_advisory_notification_sent` results as {channel result}."[thunk](let [events (atom [])]- (with-redefs [analytics/track-event! (fn [_schema data & _] (swap! events conj data))]+ (mt/with-dynamic-fn-redefs [analytics/track-event! (fn [_schema data & _] (swap! events conj data))](thunk))(into {} (for [{:keys [event event_detail result]} @events:when (= "security_advisory_notification_sent" event)]diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/index_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/index_test.cljindex 434385e3a12..86079a9526d 100644--- a/enterprise/backend/test/metabase_enterprise/semantic_search/index_test.clj+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/index_test.clj@@ -798,10 +798,10 @@(is (= [readable-id] (map :id result)))))))))(testing "memoizes permission check per collection_id across docs"(let [calls (atom 0)- real-helper perms/can-read-via-parent-collection?]- (with-redefs [perms/can-read-via-parent-collection? (fn [& args]- (swap! calls inc)- (apply real-helper args))]+ real-helper (mt/original-fn #'perms/can-read-via-parent-collection?)]+ (mt/with-dynamic-fn-redefs [perms/can-read-via-parent-collection? (fn [& args]+ (swap! calls inc)+ (apply real-helper args))](binding [api/*current-user-permissions-set* (atom #{"/"})](#'semantic.index/filter-read-permitted(repeat 50 {:id "1:1" :model "indexed-entity" :collection_id readable-coll-id}))@@ -872,21 +872,21 @@;; inside `specifications` loads the model namespaces that populate them.;; If the order flips, cold start caches an empty set for the JVM lifetime. Both the t2-model registry;; (dashboard) and the search-model registry (indexed-entity) must be covered.- (let [real-specs (var-get #'search/specifications)- real-t2-registry perms/collection-id-only-read-models- real-search-registry perms/collection-based-visibility-search-models- specs-loaded? (atom false)]- (with-redefs [search/specifications (fn []- (reset! specs-loaded? true)- (real-specs))- perms/collection-id-only-read-models (fn []- (if @specs-loaded?- (real-t2-registry)- #{}))- perms/collection-based-visibility-search-models (fn []- (if @specs-loaded?- (real-search-registry)- {}))]+ (let [real-specs (mt/original-fn #'search/specifications)+ real-t2-registry (mt/original-fn #'perms/collection-id-only-read-models)+ real-search-registry (mt/original-fn #'perms/collection-based-visibility-search-models)+ specs-loaded? (atom false)]+ (mt/with-dynamic-fn-redefs [search/specifications (fn []+ (reset! specs-loaded? true)+ (real-specs))+ perms/collection-id-only-read-models (fn []+ (if @specs-loaded?+ (real-t2-registry)+ #{}))+ perms/collection-based-visibility-search-models (fn []+ (if @specs-loaded?+ (real-search-registry)+ {}))](let [result (#'semantic.index/compute-collection-id-only-search-models)](is (contains? result "dashboard") "keyword-form registry populated")(is (contains? result "indexed-entity") "search-model registry populated"))))))diff --git a/enterprise/backend/test/metabase_enterprise/transforms/api_test.clj b/enterprise/backend/test/metabase_enterprise/transforms/api_test.cljindex edc48e0d288..97980cafe2b 100644--- a/enterprise/backend/test/metabase_enterprise/transforms/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/transforms/api_test.clj@@ -442,7 +442,7 @@;; if harbormaster somehow sends lock state for such a customer, or the setting gets tampered.;; (Note: pure OSS doesn't reach this branch because check-feature-enabled! 402s earlier on;; missing premium features.)- (with-redefs [premium-features/transform-metered-as (constantly nil)]+ (mt/with-dynamic-fn-redefs [premium-features/transform-metered-as (constantly nil)](mt/with-temporary-setting-values [locked-meters {:transform-basic-runs true:transform-advanced-runs true}](mt/user-http-request :crowberto :post 202diff --git a/modules/drivers/athena/test/metabase/driver/athena_test.clj b/modules/drivers/athena/test/metabase/driver/athena_test.cljindex 8d2532030f1..4cb1003c49f 100644--- a/modules/drivers/athena/test/metabase/driver/athena_test.clj+++ b/modules/drivers/athena/test/metabase/driver/athena_test.clj@@ -250,7 +250,7 @@(deftest hard-coded-iam-credential-handling(testing "When not hosted"- (with-redefs [premium-features/is-hosted? (constantly false)]+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly false)](testing "Specifying access-key will not use credential chain"(is (not (contains?(sql-jdbc.conn/connection-details->spec :athena {:region "us-west-2" :access_key "abc123"})@@ -260,7 +260,7 @@(sql-jdbc.conn/connection-details->spec :athena {:region "us-west-2"}):CredentialsProvider)))))(testing "When hosted"- (with-redefs [premium-features/is-hosted? (constantly true)]+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly true)](testing "Specifying access-key will not use credential chain"(is (not (contains?(sql-jdbc.conn/connection-details->spec :athena {:region "us-west-2" :access_key "abc123"})diff --git a/modules/drivers/oracle/test/metabase/driver/oracle_test.clj b/modules/drivers/oracle/test/metabase/driver/oracle_test.cljindex 2cfed3c0c4a..03f01ab8665 100644--- a/modules/drivers/oracle/test/metabase/driver/oracle_test.clj+++ b/modules/drivers/oracle/test/metabase/driver/oracle_test.clj@@ -271,7 +271,7 @@(deftest connection-properties-test(testing "Connection properties should be returned properly (including transformation of secret types)"- (with-redefs [premium-features/is-hosted? (constantly false)]+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly false)](let [expected [{:type :group:fields [{:name "host"}{:name "port"}]}diff --git a/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj b/modules/drivers/snowflake/test/metabase/driver/snowflake_test.cljindex 728b9f5591e..afa995a0dbc 100644--- a/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj+++ b/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj@@ -798,15 +798,14 @@(testing "the FK path passes raw names to the dynamic table check (#78541)"(let [dynamic-table-args (atom nil)fk-args (atom nil)]- (with-redefs [driver.snowflake/dynamic-table?- (fn [_conn db-name schema table-name]- (reset! dynamic-table-args [db-name schema table-name])- false)-- sql-jdbc.sync/reducible-table-fks-from-jdbc-metadata- (fn [_metadata db-name schema table-name]- (reset! fk-args [db-name schema table-name])- [])]+ (mt/with-dynamic-fn-redefs [driver.snowflake/dynamic-table?+ (fn [_conn db-name schema table-name]+ (reset! dynamic-table-args [db-name schema table-name])+ false)+ sql-jdbc.sync/reducible-table-fks-from-jdbc-metadata+ (fn [_metadata db-name schema table-name]+ (reset! fk-args [db-name schema table-name])+ [])](#'driver.snowflake/reducible-table-fks-from-jdbc-metadata(reify java.sql.Connection) (reify java.sql.DatabaseMetaData) "MY_DB" "RAW_DATA" "MY_TABLE"))(is (= ["MY_DB" "RAW_DATA" "MY_TABLE"] @dynamic-table-args))diff --git a/test/metabase/collections_rest/api_test.clj b/test/metabase/collections_rest/api_test.cljindex d2495060eff..7bdd83a1311 100644--- a/test/metabase/collections_rest/api_test.clj+++ b/test/metabase/collections_rest/api_test.clj@@ -1886,14 +1886,11 @@(testing "The snippets namespace is unpaginated, but a count-only request still keeps its LIMIT"(mt/with-temp [:model/NativeQuerySnippet _ {:name "UXW5016 root snippet"}](mt/with-test-user :crowberto- (let [queries (atom [])- real-query mdb/query- this-thread (Thread/currentThread)]- ;; `with-redefs` is global, so only record what this thread asks for.- (with-redefs [mdb/query (fn [query & args]- (when (identical? this-thread (Thread/currentThread))- (swap! queries conj query))- (apply real-query query args))]+ (let [queries (atom [])+ real-query (mt/original-fn #'mdb/query)]+ (mt/with-dynamic-fn-redefs [mdb/query (fn [query & args]+ (swap! queries conj query)+ (apply real-query query args))](request/with-limit-and-offset 0 0(is (pos? (:total (collections.children/collection-children(assoc collection/root-collection :namespace "snippets")diff --git a/test/metabase/contextual_interestingness/core_test.clj b/test/metabase/contextual_interestingness/core_test.cljindex cacba37e61c..e81f6fbfd65 100644--- a/test/metabase/contextual_interestingness/core_test.clj+++ b/test/metabase/contextual_interestingness/core_test.clj@@ -264,11 +264,11 @@(testing "when the caller already has chart stats, the prompt is built from them without recomputing";; The explorations runner computes deep stats for every chart it persists; the scorer used to;; throw those away and run the whole stats pipeline again (shallow) just to render the prompt.- (let [real-compute interestingness/compute-chart-stats+ (let [real-compute (mt/original-fn #'interestingness/compute-chart-stats)stats (real-compute chart-config {:deep? true})computes (atom 0)]- (with-redefs [interestingness/compute-chart-stats- (fn [config opts] (swap! computes inc) (real-compute config opts))]+ (mt/with-dynamic-fn-redefs [interestingness/compute-chart-stats+ (fn [config opts] (swap! computes inc) (real-compute config opts))](let [msg (#'contextual-interestingness.llm/build-user-message{:chart-config chart-config:context-string "Why is revenue down this month?"@@ -279,10 +279,10 @@(deftest build-user-message-computes-stats-when-not-supplied-test(testing "callers that pass no :stats still get a stats-backed representation"- (let [real-compute interestingness/compute-chart-stats+ (let [real-compute (mt/original-fn #'interestingness/compute-chart-stats)computes (atom 0)]- (with-redefs [interestingness/compute-chart-stats- (fn [config opts] (swap! computes inc) (real-compute config opts))]+ (mt/with-dynamic-fn-redefs [interestingness/compute-chart-stats+ (fn [config opts] (swap! computes inc) (real-compute config opts))](let [msg (#'contextual-interestingness.llm/build-user-message{:chart-config chart-config:context-string "Why is revenue down this month?"})]@@ -291,10 +291,10 @@(deftest score-and-describe-threads-stats-to-the-prompt-test(testing ":stats passed to the public entry point reaches the prompt builder"- (let [real-compute interestingness/compute-chart-stats+ (let [real-compute (mt/original-fn #'interestingness/compute-chart-stats)computes (atom 0)]- (with-redefs [interestingness/compute-chart-stats- (fn [config opts] (swap! computes inc) (real-compute config opts))]+ (mt/with-dynamic-fn-redefs [interestingness/compute-chart-stats+ (fn [config opts] (swap! computes inc) (real-compute config opts))](let [stats (real-compute chart-config {:deep? true})](reset! computes 0)(is (some? (message-content (captured-messages! {:stats stats}) "user")))diff --git a/test/metabase/dashboards_rest/api_test.clj b/test/metabase/dashboards_rest/api_test.cljindex 43264b587a7..f962236cc52 100644--- a/test/metabase/dashboards_rest/api_test.clj+++ b/test/metabase/dashboards_rest/api_test.clj@@ -701,13 +701,13 @@(mt/with-temp [:model/Dashboard {dash-id :id} {:name "My Bird Dashboard"}](let [calls (atom [])fake-pdf (.getBytes "%PDF-1.4 fake")]- (with-redefs [channel.render/render-dashboard-to-pdf- (fn [dashboard-id user-id parameters paper-key]- (swap! calls conj {:dashboard-id dashboard-id- :user-id user-id- :parameters parameters- :paper-key paper-key})- fake-pdf)]+ (mt/with-dynamic-fn-redefs [channel.render/render-dashboard-to-pdf+ (fn [dashboard-id user-id parameters paper-key]+ (swap! calls conj {:dashboard-id dashboard-id+ :user-id user-id+ :parameters parameters+ :paper-key paper-key})+ fake-pdf)](testing "defaults to empty parameters and A4, streaming a non-empty PDF body"(reset! calls [])(let [resp (mt/user-http-request :rasta :post 200 (format "dashboard/%d/pdf" dash-id)@@ -746,7 +746,7 @@(deftest dashboard-pdf-permissions-test(testing "POST /api/dashboard/:id/pdf requires read permission on the dashboard"- (with-redefs [channel.render/render-dashboard-to-pdf (fn [& _] (.getBytes "x"))]+ (mt/with-dynamic-fn-redefs [channel.render/render-dashboard-to-pdf (fn [& _] (.getBytes "x"))](mt/with-non-admin-groups-no-root-collection-perms(mt/with-temp [:model/Collection {coll-id :id} {:name "No-read Collection"}:model/Dashboard {dash-id :id} {:collection_id coll-id}]diff --git a/test/metabase/explorations/api_test.clj b/test/metabase/explorations/api_test.cljindex 5b11ef9409e..2492d68fc1f 100644--- a/test/metabase/explorations/api_test.clj+++ b/test/metabase/explorations/api_test.clj@@ -1683,8 +1683,8 @@(let [doc (t2/select-one :model/Document :id doc-id)];; Stub the perms check (the EQ has no inline dataset_query here) and force `create-card!`;; to blow up *after* the composite StoredResult has been inserted, exercising the rollback.- (with-redefs [query-perms/check-run-permissions-for-query (fn [_] nil)- queries/create-card! (fn [& _] (throw (ex-info "boom" {})))]+ (mt/with-dynamic-fn-redefs [query-perms/check-run-permissions-for-query (fn [_] nil)+ queries/create-card! (fn [& _] (throw (ex-info "boom" {})))](is (thrown? Throwable(eqr/create-ephemeral-card-for-exploration-queries![qid] doc-id (:collection_id doc) u@@ -1723,7 +1723,7 @@doc (t2/select-one :model/Document :id doc-id);; Stub the perms check (the synthetic EQ has no inline dataset_query) so we exercise;; the real create-card! / stored_result write path.- result (with-redefs [query-perms/check-run-permissions-for-query (fn [_] nil)]+ result (mt/with-dynamic-fn-redefs [query-perms/check-run-permissions-for-query (fn [_] nil)](eqr/create-ephemeral-card-for-exploration-queries![qid] doc-id (:collection_id doc) u{:display "bar" :visualization-settings {}}))@@ -2877,7 +2877,7 @@create hold no data perms, and `create-card!` runs the same check — the existing single-querytest stubs it for the same reason. Tests that are *about* the permission check don't use this."[& args]- (with-redefs [query-perms/check-run-permissions-for-query (fn [_] nil)]+ (mt/with-dynamic-fn-redefs [query-perms/check-run-permissions-for-query (fn [_] nil)](apply eqr/create-ephemeral-card-for-exploration-queries! args)))(deftest composite-snapshot-carries-a-data-access-token-test@@ -2940,8 +2940,8 @@;; "checked them all" are distinguishable.(t2/update! :model/ExplorationQuery (second query-ids) {:dataset_query other-q})(let [checked (atom [])]- (with-redefs [query-perms/check-run-permissions-for-query- (fn [q] (swap! checked conj q) nil)]+ (mt/with-dynamic-fn-redefs [query-perms/check-run-permissions-for-query+ (fn [q] (swap! checked conj q) nil)](eqr/create-ephemeral-card-for-exploration-queries!query-ids document-id (:collection_id doc) u{:display "bar" :visualization-settings {}}))diff --git a/test/metabase/mcp/transport_test.clj b/test/metabase/mcp/transport_test.cljindex df7ac2249b6..8497b6ad907 100644--- a/test/metabase/mcp/transport_test.clj+++ b/test/metabase/mcp/transport_test.clj@@ -438,7 +438,7 @@(testing (str "with no instance origin to check against — site-url unset or unparsable — the guard falls back ""to the Origin/Host comparison. Weaker, but a misconfigured instance degrading to the previous ""behaviour beats 403ing its own browser clients.")- (with-redefs [system/site-url (constantly nil)]+ (mt/with-dynamic-fn-redefs [system/site-url (constantly nil)](testing "same host and port is served"(is (= 200 (:status (mcp-request (jsonrpc-request "initialize"){"host" "localhost:3000" "origin" "http://localhost:3000"})))))diff --git a/test/metabase/mcp/v2/tools/question_test.clj b/test/metabase/mcp/v2/tools/question_test.cljindex de454ae64d4..41ae611e085 100644--- a/test/metabase/mcp/v2/tools/question_test.clj+++ b/test/metabase/mcp/v2/tools/question_test.clj@@ -993,16 +993,15 @@(is (=? {:type :metric :name "question-test not a question"}(t2/select-one [:model/Card :type :name] :id card-id))))))))-;; not ^:parallel: with-redefs(deftest update-save-check-uses-the-stored-card-type-test(testing "GHY-4327: the save check sees the stored card's type, not the caller's omitted card_type"(mt/with-temp [:model/Card {card-id :id} {:type :model :dataset_query (orders-query)}](mt/with-current-user (mt/user->id :crowberto)(let [seen (atom ::unset)- original queries/check-card-can-be-saved!]- (with-redefs [queries/check-card-can-be-saved! (fn [query card-type]- (reset! seen card-type)- (original query card-type))]+ original (mt/original-fn #'queries/check-card-can-be-saved!)]+ (mt/with-dynamic-fn-redefs [queries/check-card-can-be-saved! (fn [query card-type]+ (reset! seen card-type)+ (original query card-type))](let [result (call-tool #{::scope/unrestricted} (str (random-uuid)) "question_write"{:method "update" :id card-id :name "renamed"})](is (not (:isError result)) (-> result :content first :text))))diff --git a/test/metabase/metabot/tools/construct_representations_test.clj b/test/metabase/metabot/tools/construct_representations_test.cljindex fd16929d1a0..1beb6ea0ed6 100644--- a/test/metabase/metabot/tools/construct_representations_test.clj+++ b/test/metabase/metabot/tools/construct_representations_test.clj@@ -84,17 +84,17 @@([entity id & _conditions] {:model entity :id id}))(defn- with-mp-and-stubs! [f]- (with-redefs [lib-be/application-database-metadata-provider (fn [_db-id] mp)- construct/resolve-database-id-from-first-stage (fn [_] 1)- api/read-check allow-read-check- api/query-check allow-read-check]+ (mt/with-dynamic-fn-redefs [lib-be/application-database-metadata-provider (fn [_db-id] mp)+ construct/resolve-database-id-from-first-stage (fn [_] 1)+ api/read-check allow-read-check+ api/query-check allow-read-check](f)))(defn- with-ambiguous-mp-and-stubs! [f]- (with-redefs [lib-be/application-database-metadata-provider (fn [_db-id] mp-ambiguous)- construct/resolve-database-id-from-first-stage (fn [_] 1)- api/read-check allow-read-check- api/query-check allow-read-check]+ (mt/with-dynamic-fn-redefs [lib-be/application-database-metadata-provider (fn [_db-id] mp-ambiguous)+ construct/resolve-database-id-from-first-stage (fn [_] 1)+ api/read-check allow-read-check+ api/query-check allow-read-check](f)))(def ^:private mp-coerced@@ -115,10 +115,10 @@:effective-type :type/DateTime :coercion-strategy :Coercion/ISO8601->DateTime}]}))(defn- with-coerced-mp-and-stubs! [f]- (with-redefs [lib-be/application-database-metadata-provider (fn [_db-id] mp-coerced)- construct/resolve-database-id-from-first-stage (fn [_] 1)- api/read-check allow-read-check- api/query-check allow-read-check]+ (mt/with-dynamic-fn-redefs [lib-be/application-database-metadata-provider (fn [_db-id] mp-coerced)+ construct/resolve-database-id-from-first-stage (fn [_] 1)+ api/read-check allow-read-check+ api/query-check allow-read-check](f)))(def ^:private mp-temporal@@ -132,10 +132,10 @@{:id 104 :name "STATUS" :table-id 10 :base-type :type/Text}]}))(defn- with-temporal-mp-and-stubs! [f]- (with-redefs [lib-be/application-database-metadata-provider (fn [_db-id] mp-temporal)- construct/resolve-database-id-from-first-stage (fn [_] 1)- api/read-check allow-read-check- api/query-check allow-read-check]+ (mt/with-dynamic-fn-redefs [lib-be/application-database-metadata-provider (fn [_db-id] mp-temporal)+ construct/resolve-database-id-from-first-stage (fn [_] 1)+ api/read-check allow-read-check+ api/query-check allow-read-check](f)))(defn- query-data@@ -257,17 +257,17 @@;; This fixture's MP-name is "Sample Database". We DON'T stub `resolve-database-id-from-first-stage`;; here - we want the actual function to run against `name = "Sample"` and observe the;; not-found behaviour.- (with-redefs [lib-be/application-database-metadata-provider (fn [_db-id] mp-sample-database)- construct/resolve-database-id-from-first-stage- (fn [parsed]- (let [db-name (get-in parsed ["stages" 0 "source-table" 0])]- (if (= db-name "Sample Database")- 1- (throw (ex-info (str "Unknown database: `" db-name "`.")- {:agent-error? true- :status-code 400- :error :unknown-database- :database db-name})))))]+ (mt/with-dynamic-fn-redefs [lib-be/application-database-metadata-provider (fn [_db-id] mp-sample-database)+ construct/resolve-database-id-from-first-stage+ (fn [parsed]+ (let [db-name (get-in parsed ["stages" 0 "source-table" 0])]+ (if (= db-name "Sample Database")+ 1+ (throw (ex-info (str "Unknown database: `" db-name "`.")+ {:agent-error? true+ :status-code 400+ :error :unknown-database+ :database db-name})))))](let [query (query-data{"lib/type" "mbql/query""stages" [{"lib/type" "mbql.stage/mbql"@@ -436,17 +436,17 @@"DB surfaces `:unknown-database` at the `resolve-database-id-from-first-stage`\n""step, reflagged `:agent-error?` for the LLM.");; No with-mp-and-stubs! - we want the DB-name-not-found path to trigger.- (with-redefs [lib-be/application-database-metadata-provider (fn [_db-id] mp)- construct/resolve-database-id-from-first-stage- (fn [parsed]- (let [db-name (get-in parsed ["stages" 0 "source-table" 0])]- (if (= db-name "Sample")- 1- (throw (ex-info (str "Unknown database: `" db-name "`.")- {:agent-error? true- :status-code 400- :error :unknown-database- :database db-name})))))]+ (mt/with-dynamic-fn-redefs [lib-be/application-database-metadata-provider (fn [_db-id] mp)+ construct/resolve-database-id-from-first-stage+ (fn [parsed]+ (let [db-name (get-in parsed ["stages" 0 "source-table" 0])]+ (if (= db-name "Sample")+ 1+ (throw (ex-info (str "Unknown database: `" db-name "`.")+ {:agent-error? true+ :status-code 400+ :error :unknown-database+ :database db-name})))))](try(construct/execute-representations-query(query-data@@ -1198,10 +1198,10 @@record (fn ([obj] obj)([entity id] (swap! checked conj [entity id]) {:model entity :id id})([entity id & _] (swap! checked conj [entity id]) {:model entity :id id}))]- (with-redefs [lib-be/application-database-metadata-provider (fn [_] mp)- construct/resolve-database-id-from-first-stage (fn [_] 1)- api/read-check record- api/query-check record]+ (mt/with-dynamic-fn-redefs [lib-be/application-database-metadata-provider (fn [_] mp)+ construct/resolve-database-id-from-first-stage (fn [_] 1)+ api/read-check record+ api/query-check record](f))(into #{} (comp (filter (fn [[m _]] (= m :model/Table))) (map second)) @checked)))@@ -1238,10 +1238,10 @@(if (and (= entity :model/Table) (= id 20))(throw (ex-info "You don't have permissions to do that." {:status-code 403})){:model entity :id id})))]- (with-redefs [lib-be/application-database-metadata-provider (fn [_] mp)- construct/resolve-database-id-from-first-stage (fn [_] 1)- api/read-check deny-table-20- api/query-check deny-table-20]+ (mt/with-dynamic-fn-redefs [lib-be/application-database-metadata-provider (fn [_] mp)+ construct/resolve-database-id-from-first-stage (fn [_] 1)+ api/read-check deny-table-20+ api/query-check deny-table-20](try(construct/execute-representations-query(query-datadiff --git a/test/metabase/metabot/tools/resources_test.clj b/test/metabase/metabot/tools/resources_test.cljindex 54c2eef5243..b9fb4c48107 100644--- a/test/metabase/metabot/tools/resources_test.clj+++ b/test/metabase/metabot/tools/resources_test.clj@@ -795,7 +795,7 @@:target_db_id db-id:table target-table}](testing "when user CAN read the target, it appears in the output"- (with-redefs [transforms.core/get-transform (constantly stub-transform)]+ (mt/with-dynamic-fn-redefs [transforms.core/get-transform (constantly stub-transform)](let [{:keys [output]} (read-resource/read-resource{:uris ["metabase://transform/999/target"]})](is (str/includes? output "TARGET-TABLE")diff --git a/test/metabase/metrics/permissions_test.clj b/test/metabase/metrics/permissions_test.cljindex 7f7b53e15e4..3f2ee0bbb54 100644--- a/test/metabase/metrics/permissions_test.clj+++ b/test/metabase/metrics/permissions_test.clj@@ -239,7 +239,7 @@;; Two metrics × two dimensions all live on the Orders table -> a single distinct;; (db, table), so the access check must fire exactly once.(mt/with-test-user :rasta- (with-redefs [perms/user-has-permission-for-table? (fn [& _] (swap! calls inc) true)]+ (mt/with-dynamic-fn-redefs [perms/user-has-permission-for-table? (fn [& _] (swap! calls inc) true)](metrics.perms/filter-dimensions-for-user-batch [(mk) (mk)])))(is (= 1 @calls)))))diff --git a/test/metabase/models/resolution_test.clj b/test/metabase/models/resolution_test.cljindex e27f5a9e8a0..56472d83245 100644--- a/test/metabase/models/resolution_test.clj+++ b/test/metabase/models/resolution_test.clj@@ -5,6 +5,7 @@[metabase.classloader.core :as classloader][metabase.config.core :as config][metabase.models.resolution :as models.resolution]+ [metabase.test :as mt][toucan2.core :as t2]))(deftest ^:parallel table-name-resolution-test@@ -53,14 +54,14 @@"deftransforms / define-before-insert side effects), so short-circuiting on it let concurrent ""first-access on another thread use the model before its transforms were registered.")(let [required (atom [])]- (with-redefs [classloader/require (fn [& args] (swap! required into args))]+ (mt/with-dynamic-fn-redefs [classloader/require (fn [& args] (swap! required into args))](t2/resolve-model :model/QueryExecution))(is (contains? (set @required) 'metabase.queries.models.query-execution)))))(deftest resolve-model-ignores-unknown-model-keywords-test(testing "resolve-model does not attempt to require a namespace for a `model`-namespaced keyword that is not a known model"(let [required (atom [])]- (with-redefs [classloader/require (fn [& args] (swap! required into args))]+ (mt/with-dynamic-fn-redefs [classloader/require (fn [& args] (swap! required into args))](t2/resolve-model :model/DefinitelyNotARealModel))(is (empty? @required)"should not call classloader/require (which would blow up on a nil namespace) for unknown models"))))diff --git a/test/metabase/mq/init_test.clj b/test/metabase/mq/init_test.cljindex 18d5515ef8f..0aa4b990ffb 100644--- a/test/metabase/mq/init_test.clj+++ b/test/metabase/mq/init_test.clj@@ -14,10 +14,10 @@(testing "with no explicit queue-backend setting"(mt/with-temporary-setting-values [queue-backend nil](testing "defaults to quartz when the scheduler is enabled"- (with-redefs [task/scheduler-disabled? (constantly false)]+ (mt/with-dynamic-fn-redefs [task/scheduler-disabled? (constantly false)](is (= :queue.backend/quartz (#'mq.init/resolve-queue-be)))))(testing "defaults to memory when the scheduler is disabled"- (with-redefs [task/scheduler-disabled? (constantly true)]+ (mt/with-dynamic-fn-redefs [task/scheduler-disabled? (constantly true)](is (= :queue.backend/memory (#'mq.init/resolve-queue-be))))))))(deftest resolve-queue-be-explicit-test@@ -26,30 +26,30 @@["memory" false :queue.backend/memory]["memory" true :queue.backend/memory]]](mt/with-temporary-setting-values [queue-backend setting-value]- (with-redefs [task/scheduler-disabled? (constantly disabled?)]+ (mt/with-dynamic-fn-redefs [task/scheduler-disabled? (constantly disabled?)](is (= expected (#'mq.init/resolve-queue-be))))))))(deftest startup-validation-test(testing "an explicitly configured quartz backend + disabled scheduler aborts startup"(mt/with-temporary-setting-values [queue-backend "quartz"]- (with-redefs [task/scheduler-disabled? (constantly true)]+ (mt/with-dynamic-fn-redefs [task/scheduler-disabled? (constantly true)](is (thrown-with-msg? ExceptionInfo #"scheduler is disabled"(startup/def-startup-validation! ::mq.init/MqBackendValidation))))))(testing "validation passes when"(testing "quartz is merely the default (a disabled scheduler falls back to memory)"(mt/with-temporary-setting-values [queue-backend nil]- (with-redefs [task/scheduler-disabled? (constantly true)]+ (mt/with-dynamic-fn-redefs [task/scheduler-disabled? (constantly true)](is (nil? (startup/def-startup-validation! ::mq.init/MqBackendValidation))))))(testing "quartz is explicit and the scheduler is enabled"(mt/with-temporary-setting-values [queue-backend "quartz"]- (with-redefs [task/scheduler-disabled? (constantly false)]+ (mt/with-dynamic-fn-redefs [task/scheduler-disabled? (constantly false)](is (nil? (startup/def-startup-validation! ::mq.init/MqBackendValidation))))))(testing "memory is explicit and the scheduler is disabled"(mt/with-temporary-setting-values [queue-backend "memory"]- (with-redefs [task/scheduler-disabled? (constantly true)]+ (mt/with-dynamic-fn-redefs [task/scheduler-disabled? (constantly true)](is (nil? (startup/def-startup-validation! ::mq.init/MqBackendValidation)))))))(testing "an unknown explicit backend aborts startup"(mt/with-temporary-setting-values [queue-backend "bogus"]- (with-redefs [task/scheduler-disabled? (constantly false)]+ (mt/with-dynamic-fn-redefs [task/scheduler-disabled? (constantly false)](is (thrown-with-msg? ExceptionInfo #"Invalid queue backend"(startup/def-startup-validation! ::mq.init/MqBackendValidation)))))))diff --git a/test/metabase/mq/queue/outbox_test.clj b/test/metabase/mq/queue/outbox_test.cljindex 0ceea51c929..fc89fa74c39 100644--- a/test/metabase/mq/queue/outbox_test.clj+++ b/test/metabase/mq/queue/outbox_test.clj@@ -230,7 +230,7 @@id (t2/insert-returning-pk! :queue_message_outbox{:queue_name "outbox-require" :payload pl})](binding [q.backend/*backend* q.quartz/backend]- (with-redefs [task/scheduler-disabled? (constantly true)]+ (mt/with-dynamic-fn-redefs [task/scheduler-disabled? (constantly true)](outbox/publish-outbox-rows!(atom {:metabase.mq.queue.outbox/rows[{:id id :channel :queue/outbox-require :payload pl}]}))))diff --git a/test/metabase/mq/queue/quartz_test.clj b/test/metabase/mq/queue/quartz_test.cljindex e79d1a6b4ab..24c642ae565 100644--- a/test/metabase/mq/queue/quartz_test.clj+++ b/test/metabase/mq/queue/quartz_test.clj@@ -298,7 +298,7 @@;; and silently never delivered; throwing keeps outbox rows for the recovery sweep and lets the;; publish buffer retry/loudly drop, same as the nil-scheduler case above.(mt/with-temp-scheduler!- (with-redefs [task/scheduler-disabled? (constantly true)]+ (mt/with-dynamic-fn-redefs [task/scheduler-disabled? (constantly true)](let [queue (keyword "queue" (str "quartz-disabled-" (random-uuid)))](is (thrown-with-msg?clojure.lang.ExceptionInfo #"scheduler is not running"diff --git a/test/metabase/premium_features/rest/api_test.clj b/test/metabase/premium_features/rest/api_test.cljindex 1d64ccae503..489310afc96 100644--- a/test/metabase/premium_features/rest/api_test.clj+++ b/test/metabase/premium_features/rest/api_test.clj@@ -78,6 +78,7 @@(deftest token-refresh-sets-premium-features-cookie-test(testing "POST /api/premium-features/token/refresh sets the premium-features-last-updated cookie";; user-real-request hits a real Jetty server; handler thread doesn't inherit *local-redefs*.+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}(with-redefs [premium-features/token-status (constantly fake-token-status)premium-features/premium-embedding-token (constantly nil)](let [cs (cookies/cookie-store)]diff --git a/test/metabase/pulse/dashboard_subscription_test.clj b/test/metabase/pulse/dashboard_subscription_test.cljindex f4fee4ce8fe..9ad26f1a0ce 100644--- a/test/metabase/pulse/dashboard_subscription_test.clj+++ b/test/metabase/pulse/dashboard_subscription_test.clj@@ -328,10 +328,8 @@:fixture(fn [_ thunk]- ;; `with-redefs`: wrap-function returns a reify implementing only fixed `invoke` arities. The- ;; dynamic proxy invokes through `apply`, which needs `applyTo` and throws AbstractMethodError.- #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}- (with-redefs [body/attached-results-text (pulse.test-util/wrap-function @#'body/attached-results-text)]+ (mt/with-dynamic-fn-redefs [body/attached-results-text+ (pulse.test-util/wrap-function (mt/original-fn #'body/attached-results-text))](thunk))):assert@@ -377,10 +375,10 @@pulse-results)))(testing "attached-results-text should be invoked exactly once"(is (= 1- (count (pulse.test-util/input @#'body/attached-results-text)))))+ (count (pulse.test-util/input (mt/dynamic-value #'body/attached-results-text))))))(testing "attached-results-text should return nil since it's a slack message"(is (= [nil]- (pulse.test-util/output @#'body/attached-results-text))))))}}))+ (pulse.test-util/output (mt/dynamic-value #'body/attached-results-text)))))))}}))(deftest virtual-card-test(tests!@@ -1234,8 +1232,9 @@:table.cell_column "count"}};; Slack rasterizes the rendered hiccup; wrap the rasterizer to see what it was given:fixture (fn [_ thunk]- (with-redefs [channel.render/png-from-render-info- (pulse.test-util/wrap-function @#'channel.render/png-from-render-info)]+ (mt/with-dynamic-fn-redefs [channel.render/png-from-render-info+ (pulse.test-util/wrap-function+ (mt/original-fn #'channel.render/png-from-render-info))](thunk))):assert@@ -1248,7 +1247,7 @@#">Product → Category</th>")))):slack(fn [_ _]- (let [[[rendered-info]] (pulse.test-util/input @#'channel.render/png-from-render-info)+ (let [[[rendered-info]] (pulse.test-util/input (mt/dynamic-value #'channel.render/png-from-render-info))h (html (:content rendered-info))](testing "the hiccup handed to the rasterizer is the pivoted grid"(is (str/includes? h ">Facebook</th>"))@@ -1719,13 +1718,13 @@(testing "A channel with :include_pdf attaches a server-rendered PDF of the whole dashboard (#_subs)"(let [render-args (atom nil)];; Stub the renderer: avoid producing a real PDF, and capture the args it's called with.- (with-redefs [channel.render/render-dashboard-to-pdf- (fn [dashboard-id user-id parameters & [_paper-key parts]]- (reset! render-args {:dashboard-id dashboard-id- :user-id user-id- :parameters parameters- :parts parts})- (.getBytes "%PDF-1.4 stub" "UTF-8"))]+ (mt/with-dynamic-fn-redefs [channel.render/render-dashboard-to-pdf+ (fn [dashboard-id user-id parameters & [_paper-key parts]]+ (reset! render-args {:dashboard-id dashboard-id+ :user-id user-id+ :parameters parameters+ :parts parts})+ (.getBytes "%PDF-1.4 stub" "UTF-8"))](mt/with-temp [:model/Card {card-id :id} {:name pulse.test-util/card-name:dataset_query (mt/mbql-query orders {:limit 1})}:model/Dashboard {dashboard-id :id} {:name "Aviary KPIs"}@@ -1761,8 +1760,8 @@(deftest dashboard-sub-no-pdf-by-default-test(testing "Without :include_pdf, the renderer is not invoked and no PDF is attached"(let [called? (atom false)]- (with-redefs [channel.render/render-dashboard-to-pdf- (fn [& _] (reset! called? true) (byte-array 0))]+ (mt/with-dynamic-fn-redefs [channel.render/render-dashboard-to-pdf+ (fn [& _] (reset! called? true) (byte-array 0))](mt/with-temp [:model/Card {card-id :id} {:name pulse.test-util/card-name:dataset_query (mt/mbql-query orders {:limit 1})}:model/Dashboard {dashboard-id :id} {:name "Aviary KPIs"}@@ -1801,11 +1800,11 @@:channel_type "slack":details {:channel "#general" :include_pdf true}}](let [render-args (atom nil)]- (with-redefs [channel.render/render-dashboard-to-pdf- (fn [dashboard-id user-id parameters & [_paper-key parts]]- (reset! render-args {:dashboard-id dashboard-id :user-id user-id- :parameters parameters :parts parts})- (.getBytes "%PDF-1.4 stub" "UTF-8"))]+ (mt/with-dynamic-fn-redefs [channel.render/render-dashboard-to-pdf+ (fn [dashboard-id user-id parameters & [_paper-key parts]]+ (reset! render-args {:dashboard-id dashboard-id :user-id user-id+ :parameters parameters :parts parts})+ (.getBytes "%PDF-1.4 stub" "UTF-8"))](pulse.test-util/slack-test-setup!(let [results (pulse.test-util/with-captured-channel-send-messages!(pulse.send/send-pulse! (t2/select-one :model/Pulse pulse-id)))diff --git a/test/metabase/pulse/send_test.clj b/test/metabase/pulse/send_test.cljindex dcbd6dd9e74..7cb68ea05b7 100644--- a/test/metabase/pulse/send_test.clj+++ b/test/metabase/pulse/send_test.clj@@ -245,10 +245,8 @@:fixture(fn [_ thunk]- ;; `with-redefs`: wrap-function returns a reify implementing only fixed `invoke` arities. The- ;; dynamic proxy invokes through `apply`, which needs `applyTo` and throws AbstractMethodError.- #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}- (with-redefs [body/attached-results-text (pulse.test-util/wrap-function @#'body/attached-results-text)]+ (mt/with-dynamic-fn-redefs [body/attached-results-text+ (pulse.test-util/wrap-function (mt/original-fn #'body/attached-results-text))](thunk))):assert@@ -276,10 +274,10 @@message)))(testing "attached-results-text should be invoked exactly once"(is (= 1- (count (pulse.test-util/input @#'body/attached-results-text)))))+ (count (pulse.test-util/input (mt/dynamic-value #'body/attached-results-text))))))(testing "attached-results-text should return nil since it's a slack message"(is (= [nil]- (pulse.test-util/output @#'body/attached-results-text))))))}}+ (pulse.test-util/output (mt/dynamic-value #'body/attached-results-text)))))))}}"11 rows in the results no longer causes a CSV attachment per issue #36441."{:card (pulse.test-util/checkins-query-card {:aggregation nil, :limit 11})diff --git a/test/metabase/pulse/test_util.clj b/test/metabase/pulse/test_util.cljindex d2e9a556e98..6190cc0caee 100644--- a/test/metabase/pulse/test_util.clj+++ b/test/metabase/pulse/test_util.clj@@ -105,7 +105,9 @@(invoke [_ x1 x2 x3 x4 x5](invoke-with-wrapping input output func [x1 x2 x3 x4 x5]))(invoke [_ x1 x2 x3 x4 x5 x6]- (invoke-with-wrapping input output func [x1 x2 x3 x4 x5 x6])))))+ (invoke-with-wrapping input output func [x1 x2 x3 x4 x5 x6]))+ (applyTo [_ args]+ (invoke-with-wrapping input output func (vec args))))))(defn thunk->boolean [{:keys [attachments] :as result}](assoc result :attachments (for [attachment-info attachments]diff --git a/test/metabase/sync/analyze/data_sensitivity_test.clj b/test/metabase/sync/analyze/data_sensitivity_test.cljindex 45536596436..a60baf3b14e 100644--- a/test/metabase/sync/analyze/data_sensitivity_test.clj+++ b/test/metabase/sync/analyze/data_sensitivity_test.clj@@ -107,7 +107,7 @@:model/Field foo {:table_id (:id table) :name "foo" :base_type :type/Text}](sync.data-sensitivity/scan-fields-for-db! db nil)(is (= :PUBLIC (label foo)))- (with-redefs [analyze/infer-data-sensitivity (constantly :PHI)]+ (mt/with-dynamic-fn-redefs [analyze/infer-data-sensitivity (constantly :PHI)](testing "a scheduled scan does not revisit PUBLIC fields even when the rules would now match"(is (= {:fields-scanned 0 :fields-labeled 0 :fields-failed 0}(sync.data-sensitivity/scan-fields-for-db! db nil)))@@ -189,7 +189,7 @@(field-user-settings/upsert-user-settings notes {:data_sensitivity :PHI})(sync.data-sensitivity/scan-data-sensitivity! db)(is (= :PII (sync-label ssn)))- (with-redefs [analyze/infer-data-sensitivity (constantly :SEC_KEY)]+ (mt/with-dynamic-fn-redefs [analyze/infer-data-sensitivity (constantly :SEC_KEY)](testing "a forced scan leaves a categorized field on its old label"(sync.data-sensitivity/scan-data-sensitivity! db :force? true)(is (= :PII (sync-label ssn))))@@ -207,7 +207,7 @@:model/Table table {:db_id (:id db) :name "app_users"}:model/Field ssn {:table_id (:id table) :name "ssn" :base_type :type/Text}](let [calls (atom 0)]- (with-redefs [analyze/infer-data-sensitivity (fn [& _] (swap! calls inc) (throw (ex-info "boom" {})))]+ (mt/with-dynamic-fn-redefs [analyze/infer-data-sensitivity (fn [& _] (swap! calls inc) (throw (ex-info "boom" {})))](testing "a throwing rule counts as scanned and failed and leaves the field unscanned"(is (= {:fields-scanned 1 :fields-labeled 0 :fields-failed 1}(sync.data-sensitivity/scan-data-sensitivity! db)))diff --git a/test/metabase/sync/analyze/interestingness_test.clj b/test/metabase/sync/analyze/interestingness_test.cljindex b374536f726..78c9dcb7a84 100644--- a/test/metabase/sync/analyze/interestingness_test.clj+++ b/test/metabase/sync/analyze/interestingness_test.clj@@ -51,9 +51,9 @@:model/Table table {:db_id (:id database)}:model/Field _field {:table_id (:id table)}](let [calls (atom 0)]- (with-redefs [interestingness/dimension-interestingness (fn [_field]- (swap! calls inc)- (throw (ex-info "boom" {})))]+ (mt/with-dynamic-fn-redefs [interestingness/dimension-interestingness (fn [_field]+ (swap! calls inc)+ (throw (ex-info "boom" {})))](is (= {:fields-scored 0 :fields-failed 1}(#'sync.interestingness/score-missing-leftovers! database)))(is (= 1 @calls))diff --git a/test/metabase/test/util/dynamic_redefs.clj b/test/metabase/test/util/dynamic_redefs.cljindex 88126b1087d..387022daddf 100644--- a/test/metabase/test/util/dynamic_redefs.clj+++ b/test/metabase/test/util/dynamic_redefs.clj@@ -18,18 +18,27 @@Generous enough to permit deliberate recursion, low enough to fail fast before SOE."128)+(defn- proxy-original+ "The original that the proxy at the root of `a-var` was built with, or nil when the root is not its proxy."+ [^Var a-var]+ (let [root (.getRawRoot a-var)]+ (when (identical? a-var (::proxy-for (meta root)))+ (::original (meta root)))))+(defn dynamic-value"Get the value of this var that is in scope. It is the unpatched version if there is no override."[a-var]+ ;; Callers also pass the proxy itself, which carries its original.(get *local-redefs* a-var- (get (meta a-var) ::original)))+ (if (var? a-var)+ (proxy-original a-var)+ (::original (meta a-var)))))(defn original-fn- "Return the original (unpatched) function for `a-var`. If the var has been- patched by [[with-dynamic-fn-redefs]], returns the stored original; otherwise- returns the var's current root value."+ "Return the original (unpatched) function for `a-var`.+ That is the root it had when [[with-dynamic-fn-redefs]] proxied it, or its current root if it is not proxied."[a-var]- (or (::original (meta a-var)) @a-var))+ (or (proxy-original a-var) @a-var))(defn- var->proxy"Build a proxy function to intercept the given var. The proxy checks the current scope for what to call.@@ -37,21 +46,23 @@Accepts any `IFn` root value — keywords and collections work via their `IFn` impl(`(:a {:a 1})` → `1`, `({:a 1} :a)` → `1`), so the proxy's `apply` delegates correctly."- [a-var]- (let [v @a-var]- (when-not (ifn? v)- (throw (ex-info (str "Cannot proxy non-IFn values: " a-var) {:var a-var, :value v})))- (when (instance? MultiFn v)- (throw (ex-info (str "Cannot proxy multimethods: " a-var ". "- "with-dynamic-fn-redefs replaces the var's root with a proxy, which breaks "- "dispatch and pollutes the JVM for other tests. Use defmethod (or add-method) "- "with a dedicated test dispatch value instead.")- {:var a-var}))))+ [a-var original]+ (when-not (ifn? original)+ (throw (ex-info (str "Cannot proxy non-IFn values: " a-var) {:var a-var, :value original})))+ (when (instance? MultiFn original)+ (throw (ex-info (str "Cannot proxy multimethods: " a-var ". "+ "with-dynamic-fn-redefs replaces the var's root with a proxy, which breaks "+ "dispatch and pollutes the JVM for other tests. Use defmethod (or add-method) "+ "with a dedicated test dispatch value instead.")+ {:var a-var})))+ ;; Each proxy keeps its own original. Something else can put a different root over the proxy and a later patch+ ;; then treats that root as the original, so an original stored on the var would be wrong for this proxy.+ ^{::proxy-for a-var, ::original original}(fn [& args](let [depth (get *proxy-depths* a-var 0)](when (> depth max-proxy-depth)- ;; Throw an Error, not an Exception: and a plain Exception gets swallowed by a `(catch Exception ...)` in the code under test,- ;; turning this diagnostic into silent, confusing behavior.+ ;; Throw an Error, not an Exception: a `(catch Exception ...)` in the code under test would swallow an Exception+ ;; and turn this diagnostic into silent, confusing behavior.(throw (AssertionError.(str "with-dynamic-fn-redefs: runaway recursion through proxy for " a-var " (depth " depth "). ""This usually means the replacement fn calls the redefined var directly "@@ -59,21 +70,18 @@"Use (metabase.test.util.dynamic-redefs/original-fn " (pr-str a-var) ") ""to capture the unpatched function."))))(binding [*proxy-depths* (assoc *proxy-depths* a-var (inc depth))]- (let [current-f (dynamic-value a-var)]+ (let [current-f (get *local-redefs* a-var original)](apply current-f args))))))(defn patch-vars!"Rebind the given vars with proxies that wrap the original functions."[vars]- (let [unpatched-vars (remove #(::patched? (meta %)) vars)]- (doseq [^Var a-var unpatched-vars]- (locking a-var- (when-not (::patched? (meta a-var))- (let [old-val (.getRawRoot a-var)- patch-meta #(assoc % ::original old-val ::patched? true)]- (.bindRoot a-var (with-meta (var->proxy a-var)- (patch-meta (meta (get *local-redefs* a-var)))))- (alter-meta! a-var patch-meta)))))))+ ;; Check the root rather than a flag on the var: something else can replace the root after it is patched. The watch+ ;; potemkin puts on a re-export's source copies the source's root over the re-export whenever that root changes.+ (doseq [^Var a-var (remove proxy-original vars)]+ (locking a-var+ (when-not (proxy-original a-var)+ (.bindRoot a-var (var->proxy a-var (.getRawRoot a-var)))))))(defn- sym->var [sym] `(var ~sym))@@ -96,7 +104,9 @@- Only threads that inherit the calling thread's dynamic bindings see the replacement.`future`, `core.async/go`, and `core.async/thread` convey bindings automatically; raw`Thread`, quartz/cron workers, and unwrapped `ExecutorService` tasks do not. For those- keep `with-redefs` — the root swap is visible to every thread."+ keep `with-redefs` — the root swap is visible to every thread.+ - Redefining a potemkin re-export only intercepts calls made through the re-export.+ Callers of the var it was imported from still see the original."[bindings & body](let [var->definition (bindings->var->definition bindings)]`(dodiff --git a/test/metabase/test/util_test.clj b/test/metabase/test/util_test.cljindex fcfe563abe1..dc1f687fc3a 100644--- a/test/metabase/test/util_test.clj+++ b/test/metabase/test/util_test.clj@@ -2,11 +2,14 @@"Tests for the test utils!"(:require[clojure.test :refer :all]+ [metabase.premium-features.core :as premium-features]+ [metabase.premium-features.settings :as premium-features.settings][metabase.settings.core :as setting][metabase.test :as mt][metabase.test.data :as data][metabase.util :as u][metabase.util.log :as log]+ [potemkin :as p][toucan2.core :as t2])(:import(clojure.lang Agent)@@ -169,6 +172,75 @@(if (pos? x) (counting-target (dec x)) :recursed))](is (= :recursed (counting-target 50))))))+(defn- nested-redef-target [] ::real)++;; Not ^:parallel: `with-redefs` replaces the var's root for every thread.+(deftest with-dynamic-fn-redefs-inside-with-redefs-test+ (testing "A stub that `with-redefs` puts over a proxied var is not kept as the var's original"+ (mt/with-dynamic-fn-redefs [nested-redef-target (constantly ::dynamic)]+ (is (= ::dynamic (nested-redef-target))))+ ;; The global root swap is the case under test: it puts a stub where the proxy was.+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}+ (with-redefs [nested-redef-target (constantly ::stub)]+ (mt/with-dynamic-fn-redefs [nested-redef-target (constantly ::dynamic)]+ (is (= ::dynamic (nested-redef-target)))))+ (is (= ::real (nested-redef-target)))+ (is (= ::real ((mt/original-fn #'nested-redef-target))))+ (is (= ::real ((mt/dynamic-value #'nested-redef-target))))))++(defn- reexport-source+ "The var `premium-features/is-hosted?` is imported from, checked so these tests fail if the re-export moves."+ []+ (let [src #'premium-features.settings/is-hosted?]+ (assert (contains? (.getWatches ^clojure.lang.Var src) #'premium-features/is-hosted?))+ src))++;; Not ^:parallel: patching a source, or `with-redefs` on it, replaces the re-export's root for every thread.++(deftest with-dynamic-fn-redefs-reexport-after-source-patched-test+ (testing "A redef of a potemkin re-export holds after its source var is patched"+ (let [src (reexport-source)]+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly ::reexport)]+ (is (= ::reexport (premium-features/is-hosted?))))+ (mt/with-dynamic-fn-redefs [premium-features.settings/is-hosted? (constantly ::source)]+ (is (= ::source (premium-features/is-hosted?))))+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly ::reexport)]+ (is (= ::reexport (premium-features/is-hosted?)))+ (is (not= ::reexport (@src)))))))++(deftest with-dynamic-fn-redefs-reexport-after-source-with-redefs-test+ (testing "A redef of a potemkin re-export holds after `with-redefs` on its source var"+ (reexport-source)+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly ::reexport)]+ (is (= ::reexport (premium-features/is-hosted?))))+ ;; The global root swap is the case under test: it replaces the source root without going through a proxy.+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}+ (with-redefs [premium-features.settings/is-hosted? (constantly ::global)]+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly ::reexport)]+ (is (= ::reexport (premium-features/is-hosted?)))))+ (testing "the original is not the stub that was the root when the re-export was last patched"+ (is (not= ::global ((mt/original-fn #'premium-features/is-hosted?)))))+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly ::reexport)]+ (is (= ::reexport (premium-features/is-hosted?))))))++(defn chain-source [] ::real)+(p/import-fn chain-source chain-middle)+(p/import-fn chain-middle chain-end)++;; Not ^:parallel: patching `chain-source` replaces the roots of both re-exports for every thread.+(deftest with-dynamic-fn-redefs-transitive-reexport-test+ (testing "A redef of a re-export of a re-export holds after the var at the start of the chain is patched"+ (mt/with-dynamic-fn-redefs [chain-end (constantly ::end)]+ (is (= ::end (chain-end))))+ (mt/with-dynamic-fn-redefs [chain-source (constantly ::source)]+ (is (= ::source (chain-middle)))+ (is (= ::source (chain-end))))+ (mt/with-dynamic-fn-redefs [chain-end (constantly ::end)]+ (is (= ::end (chain-end)))+ (is (= ::real (chain-middle))))+ (is (= ::real (chain-end)))+ (is (= ::real ((mt/original-fn #'chain-end))))))+(deftest ^:parallel ordered-subset?-test(is (mt/ordered-subset? [1 2 3] [1 2 3]))(is (mt/ordered-subset? [1 2 3] [1 2 1 3 4 5]))diff --git a/test/metabase/transforms/jobs_test.clj b/test/metabase/transforms/jobs_test.cljindex ffee6da399d..e2bda8cc3a5 100644--- a/test/metabase/transforms/jobs_test.clj+++ b/test/metabase/transforms/jobs_test.clj@@ -225,12 +225,12 @@;; `transform-metered-as` is `defenterprise`; the OSS impl returns nil for everything,;; which makes `transform-locked?` short-circuit to false regardless of `:locked-meters`.;; Mock the routing so the test exercises the lock-check branch under any classpath.- (with-redefs [premium-features/transform-metered-as (fn [source-type]- (case (keyword source-type)- :native "transform-basic"- :mbql "transform-basic"- :python "transform-advanced"- nil))]+ (mt/with-dynamic-fn-redefs [premium-features/transform-metered-as (fn [source-type]+ (case (keyword source-type)+ :native "transform-basic"+ :mbql "transform-basic"+ :python "transform-advanced"+ nil))](testing "scheduled run-transform! is skipped (with warn log) when the meter is locked"(mt/with-premium-features #{:hosting :transforms-basic}(mt/with-temporary-setting-values [locked-meters {:transform-basic-runs true}]@@ -266,7 +266,7 @@(is (true? @run-called?)))))))(testing "non-metered transform (transform-metered-as → nil) is never blocked by lock state";; Override the outer mock with one that returns nil for every source-type.- (with-redefs [premium-features/transform-metered-as (constantly nil)]+ (mt/with-dynamic-fn-redefs [premium-features/transform-metered-as (constantly nil)](mt/with-premium-features #{:hosting :transforms-basic}(mt/with-temporary-setting-values [locked-meters {:transform-basic-runs true:transform-advanced-runs true}]diff --git a/test/metabase/transforms/usage_test.clj b/test/metabase/transforms/usage_test.cljindex 5298a55eaf5..b1df2e5d565 100644--- a/test/metabase/transforms/usage_test.clj+++ b/test/metabase/transforms/usage_test.clj@@ -12,7 +12,7 @@"Call zero-arg `f` with [[premium-features/transform-metered-as]] redefined to returnthe given fixed `bucket` string."[bucket f]- (with-redefs [premium-features/transform-metered-as (constantly bucket)]+ (mt/with-dynamic-fn-redefs [premium-features/transform-metered-as (constantly bucket)](f)))(deftest transform-locked?-no-bucket-testdiff --git a/test/metabase/usage_metadata/batch_test.clj b/test/metabase/usage_metadata/batch_test.cljindex c819bc0bbc9..6fb7438907c 100644--- a/test/metabase/usage_metadata/batch_test.clj+++ b/test/metabase/usage_metadata/batch_test.clj@@ -336,10 +336,10 @@(insert-query! bad-hash bad-payload)(insert-query-execution! good-hash (t/offset-date-time "2026-04-13T12:00Z"))(insert-query-execution! bad-hash (t/offset-date-time "2026-04-13T13:00Z"))- (with-redefs [lib-be/normalize-query (fn [stored-query]- (if (= stored-query bad-payload)- (throw (ex-info "kaboom" {:q stored-query}))- (original stored-query)))]+ (mt/with-dynamic-fn-redefs [lib-be/normalize-query (fn [stored-query]+ (if (= stored-query bad-payload)+ (throw (ex-info "kaboom" {:q stored-query}))+ (original stored-query)))](mt/with-temporary-setting-values [usage-metadata-last-completed-day "2026-04-12"](let [result (usage-metadata.batch/process-day! bucket-date)](testing "the bad row is recorded as :normalize-error skip"diff --git a/test/metabase/warehouses_rest/api_test.clj b/test/metabase/warehouses_rest/api_test.cljindex 41c3721f768..4b904451909 100644--- a/test/metabase/warehouses_rest/api_test.clj+++ b/test/metabase/warehouses_rest/api_test.clj@@ -3290,7 +3290,7 @@(is (= "new-write-host" (get-in db [:write_data_details :host])))(is (= "original-pass" (get-in db [:write_data_details :password]))))))))(testing "Returns 402 without :writable-connection feature"- (with-redefs [premium-features/has-feature? (constantly false)]+ (mt/with-dynamic-fn-redefs [premium-features/has-feature? (constantly false)](mt/with-temp [:model/Database {db-id :id} {:engine :h2:details {:host "localhost"}}](mt/user-http-request :crowberto :put 402 (format "database/%d" db-id)