Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Warm the Kondo cache so cache-reading hooks run in CI (#82388)

Chris Truteraecbc3c3cbd2
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.edn
index e65f1a9e443..80b9f733ad8 100644
--- a/.clj-kondo/config.edn
+++ b/.clj-kondo/config.edn
@@ -930,6 +930,8 @@
{:linters {:metabase/prefer-with-dynamic-fn-redefs {:level :off}}}
metabase.util.time-test
{:linters {:metabase/prefer-with-dynamic-fn-redefs {:level :off}}}
+ metabase.lib.metadata.calculation-test
+ {:linters {:metabase/prefer-with-dynamic-fn-redefs {:level :off}}}
;; classloader sits below `util` in the module graph, so it can't use `metabase.util.log` without creating
;; a cycle; it gets to use tools.logging directly.
diff --git a/.clj-kondo/ratchets.edn b/.clj-kondo/ratchets.edn
index bb8dd9091ad..58e409196fa 100644
--- a/.clj-kondo/ratchets.edn
+++ b/.clj-kondo/ratchets.edn
@@ -26,7 +26,7 @@
:metabase/i-like-making-cams-eyes-bleed-with-horrifically-long-tests 13
:metabase/modules 24
:metabase/namespace-name 4
- :metabase/prefer-with-dynamic-fn-redefs 28
+ :metabase/prefer-with-dynamic-fn-redefs :unlimited
:metabase/test-helpers-use-non-thread-safe-functions 18
:metabase/validate-defendpoint-has-response-schema 427
:metabase/validate-defendpoint-query-params-use-kebab-case 48
@@ -59,7 +59,7 @@
:main-without-gen-class 1
:metabase/defsetting-must-specify-export 1
:metabase/defsetting-namespace 1
- :metabase/prefer-with-dynamic-fn-redefs 3
+ :metabase/prefer-with-dynamic-fn-redefs 4
:metabase/t2-query-namespace 2
:metabase/table-or-field-query 1
:missing-docstring 1
diff --git a/dev/test/metabase/core/kondo_ratchet_check_test.clj b/dev/test/metabase/core/kondo_ratchet_check_test.clj
index cd54b7a8d61..0bc17d7e502 100644
--- a/dev/test/metabase/core/kondo_ratchet_check_test.clj
+++ b/dev/test/metabase/core/kondo_ratchet_check_test.clj
@@ -103,10 +103,10 @@
thrown? (atom false)]
(binding [kondo-ratchet/*ratchets-file* (.getPath budgets)
kondo-ratchet/*module-ratchets-file* (.getPath modules)]
- (with-redefs [kondo-ratchet/known-linters (constantly (set (keys (:ignore-counts ratchets))))
- kondo-ratchet/config-suppressions (constantly {})
- kondo-ratchet/module-escape-hatches (constantly {})
- kondo-ratchet/scan (constantly occurrences)]
+ (mt/with-dynamic-fn-redefs [kondo-ratchet/known-linters (constantly (set (keys (:ignore-counts ratchets))))
+ kondo-ratchet/config-suppressions (constantly {})
+ kondo-ratchet/module-escape-hatches (constantly {})
+ kondo-ratchet/scan (constantly occurrences)]
{:lines (str/split-lines
(with-out-str
(try
@@ -193,7 +193,7 @@
:config-counts {}
:comment-exempt #{}})))]
(binding [kondo-ratchet/*ratchets-file* (.getPath budgets)]
- (with-redefs [kondo-ratchet/known-linters (constantly #{:a})]
+ (mt/with-dynamic-fn-redefs [kondo-ratchet/known-linters (constantly #{:a})]
(let [out (with-out-str
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"names 1 unknown linter: :bogus"
(kondo-ratchet/check))))]
diff --git a/dev/test/metabase/core/kondo_ratchet_test.clj b/dev/test/metabase/core/kondo_ratchet_test.clj
index 971b3aee600..5fca432c9ac 100644
--- a/dev/test/metabase/core/kondo_ratchet_test.clj
+++ b/dev/test/metabase/core/kondo_ratchet_test.clj
@@ -361,10 +361,10 @@
{:file "f.clj", :line 2, :linters [:free]}]]
(binding [kondo-ratchet/*ratchets-file* (.getPath budgets)
kondo-ratchet/*module-ratchets-file* (.getPath modules)]
- (with-redefs [kondo-ratchet/known-linters (constantly #{:free})
- kondo-ratchet/scan (constantly occurrences)
- kondo-ratchet/config-suppressions (constantly {})
- kondo-ratchet/module-escape-hatches (constantly {})]
+ (mt/with-dynamic-fn-redefs [kondo-ratchet/known-linters (constantly #{:free})
+ kondo-ratchet/scan (constantly occurrences)
+ kondo-ratchet/config-suppressions (constantly {})
+ kondo-ratchet/module-escape-hatches (constantly {})]
(is (= ["seeded :free at 2"
(str "wrote " (.getPath budgets))]
(str/split-lines (with-out-str (kondo-ratchet/fix! {:seed "free"}))))))
@@ -383,8 +383,8 @@
(spit (kondo-ratchet/render-module-ratchets {})))]
(binding [kondo-ratchet/*ratchets-file* (.getPath budgets)
kondo-ratchet/*module-ratchets-file* (.getPath modules)]
- (with-redefs [kondo-ratchet/known-linters (constantly #{:free})
- kondo-ratchet/scan (fn [] (throw (AssertionError. "scanned before validating the seed")))]
+ (mt/with-dynamic-fn-redefs [kondo-ratchet/known-linters (constantly #{:free})
+ kondo-ratchet/scan (fn [] (throw (AssertionError. "scanned before validating the seed")))]
(is (thrown-with-msg? clojure.lang.ExceptionInfo
#"^cannot seed :bogus: not a known linter -- policies must name"
(kondo-ratchet/fix! {:seed ":bogus"})))
@@ -405,10 +405,10 @@
run! #(str/split-lines (with-out-str (kondo-ratchet/fix!)))]
(binding [kondo-ratchet/*ratchets-file* (.getPath budgets)
kondo-ratchet/*module-ratchets-file* (.getPath modules)]
- (with-redefs [kondo-ratchet/known-linters (constantly #{:free :empty :gone :zero})
- kondo-ratchet/scan (constantly occurrences)
- kondo-ratchet/config-suppressions (constantly {})
- kondo-ratchet/module-escape-hatches (constantly {})]
+ (mt/with-dynamic-fn-redefs [kondo-ratchet/known-linters (constantly #{:free :empty :gone :zero})
+ kondo-ratchet/scan (constantly occurrences)
+ kondo-ratchet/config-suppressions (constantly {})
+ kondo-ratchet/module-escape-hatches (constantly {})]
(is (= ["dropped :gone (no ignores left)"
"dropped :zero (no ignores left)"
"WARNING: :unlimited policies with no ignores left: :empty -- delete an entry by hand once its linter no longer needs one"
@@ -437,10 +437,10 @@
{:api-any 2, :friend-edges 5, :uses-any 1})))]
(binding [kondo-ratchet/*ratchets-file* (.getPath budgets)
kondo-ratchet/*module-ratchets-file* (.getPath modules)]
- (with-redefs [kondo-ratchet/known-linters (constantly #{})
- kondo-ratchet/scan (constantly [])
- kondo-ratchet/config-suppressions (constantly {})
- kondo-ratchet/module-escape-hatches (constantly {:api-any 1, :friend-edges 4, :uses-any 0})]
+ (mt/with-dynamic-fn-redefs [kondo-ratchet/known-linters (constantly #{})
+ kondo-ratchet/scan (constantly [])
+ kondo-ratchet/config-suppressions (constantly {})
+ kondo-ratchet/module-escape-hatches (constantly {:api-any 1, :friend-edges 4, :uses-any 0})]
(is (= ["lowered module :api-any 2 -> 1"
"lowered module :friend-edges 5 -> 4"
"dropped module :uses-any (no escape hatches left)"
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.clj
index db794c66dfc..cbfe8a1c521 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
@@ -122,7 +122,7 @@
(mt/with-temporary-setting-values [config-from-file-sync-databases true]
(try
(let [submit-calls (atom 0)]
- (with-redefs [quick-task/submit-task! (fn [_] (swap! submit-calls inc))]
+ (mt/with-dynamic-fn-redefs [quick-task/submit-task! (fn [_] (swap! submit-calls inc))]
(testing "config entry with :is_stub true and empty :details is accepted"
(is (= :ok
(advanced-config.file/initialize!
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_permissions/models/field_values_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_permissions/models/field_values_test.clj
index 7f516d4a57f..96061a2042d 100644
--- a/enterprise/backend/test/metabase_enterprise/advanced_permissions/models/field_values_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/advanced_permissions/models/field_values_test.clj
@@ -34,10 +34,10 @@
(testing "and a warm hit is served without a detached fetch — it is one SELECT, so
handing it to a background thread costs more than it saves (GHY-2937)"
(let [detached (atom 0)
- real field-values/detached-fetch!]
- (with-redefs [field-values/detached-fetch! (fn [& args]
- (swap! detached inc)
- (apply real args))]
+ real (mt/original-fn #'field-values/detached-fetch!)]
+ (mt/with-dynamic-fn-redefs [field-values/detached-fetch! (fn [& args]
+ (swap! detached inc)
+ (apply real args))]
(params.field-values/get-or-create-field-values! field)
(is (zero? @detached)))))
(testing "changing the impersonation role creates new FieldValues"
diff --git a/enterprise/backend/test/metabase_enterprise/audit_app/audit_test.clj b/enterprise/backend/test/metabase_enterprise/audit_app/audit_test.clj
index 5d4a7be0c4e..d39f89f0264 100644
--- a/enterprise/backend/test/metabase_enterprise/audit_app/audit_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/audit_app/audit_test.clj
@@ -476,17 +476,17 @@
(try
;; stale the content checksum so the (stubbed) load runs inside the locked pipeline
(audit/last-analytics-checksum! 0)
- (with-redefs [serialization.cmd/v2-load-internal!
- (fn [& _]
- (t2/insert! :model/User (assoc (mt/with-temp-defaults :model/User) :email email))
- (reset! visible
- (deref (future
- (binding [t2.connection/*current-connectable* nil]
- (t2/exists? :model/User :email email)))
- 5000 ::timeout))
- ;; report no errors: content is already loaded from the steady state, so
- ;; letting the checksum advance leaves a consistent end state
- {:errors [] :seen []})]
+ (mt/with-dynamic-fn-redefs [serialization.cmd/v2-load-internal!
+ (fn [& _]
+ (t2/insert! :model/User (assoc (mt/with-temp-defaults :model/User) :email email))
+ (reset! visible
+ (deref (future
+ (binding [t2.connection/*current-connectable* nil]
+ (t2/exists? :model/User :email email)))
+ 5000 ::timeout))
+ ;; report no errors: content is already loaded from the steady state, so
+ ;; letting the checksum advance leaves a consistent end state
+ {:errors [] :seen []})]
(mbc/ensure-audit-db-installed!))
(testing "work committed inside the audit pipeline is visible mid-pipeline from another connection"
(is (true? @visible)))
@@ -505,8 +505,8 @@
(audit/last-analytics-checksum! 0)
;; "Boot 1": the serdes load dies partway through.
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"killed mid-load"
- (with-redefs [serialization.cmd/v2-load-internal!
- (fn [& _] (throw (ex-info "killed mid-load" {})))]
+ (mt/with-dynamic-fn-redefs [serialization.cmd/v2-load-internal!
+ (fn [& _] (throw (ex-info "killed mid-load" {})))]
(mbc/ensure-audit-db-installed!))))
(testing "the content checksum does not advance past an incomplete load"
(is (= 0 (audit/last-analytics-checksum))))
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.clj
index 187c8748ed2..1ba984696de 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
@@ -93,7 +93,7 @@
(mt/user-http-request :crowberto :post 400 (str "ee/cloud-add-ons/" product-type) {})))))
(testing "succeeds when all conditions are met"
(mt/with-premium-features #{:hosting}
- (with-redefs [hm.client/call (constantly nil)]
+ (mt/with-dynamic-fn-redefs [hm.client/call (constantly nil)]
(is (=? {}
(mt/user-http-request :crowberto :post 200 (str "ee/cloud-add-ons/" product-type) {})))))))))
@@ -147,7 +147,7 @@
(testing "is rejected as a bundle-only product type without calling the Store"
(mt/with-premium-features #{:hosting}
(let [{store-api-proxy :proxy store-api-calls :calls} (semantic.tu/spy (constantly nil))]
- (with-redefs [hm.client/call store-api-proxy]
+ (mt/with-dynamic-fn-redefs [hm.client/call store-api-proxy]
(is (=? "This add-on can only be purchased as part of a bundle."
(mt/user-http-request :crowberto :post 400 "ee/cloud-add-ons/etl-connections" {})))
(is (empty? @store-api-calls)
@@ -228,7 +228,7 @@
(testing "is rejected as a bundle-only product type without calling the Store"
(mt/with-premium-features #{:hosting}
(let [{store-api-proxy :proxy store-api-calls :calls} (semantic.tu/spy (constantly nil))]
- (with-redefs [hm.client/call store-api-proxy]
+ (mt/with-dynamic-fn-redefs [hm.client/call store-api-proxy]
(is (=? "This add-on can only be purchased as part of a bundle."
(mt/user-http-request :crowberto :delete 400 "ee/cloud-add-ons/etl-connections")))
(is (empty? @store-api-calls)
diff --git a/enterprise/backend/test/metabase_enterprise/cloud_proxy/api_test.clj b/enterprise/backend/test/metabase_enterprise/cloud_proxy/api_test.clj
index 2715e832aa6..307e95acac5 100644
--- a/enterprise/backend/test/metabase_enterprise/cloud_proxy/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/cloud_proxy/api_test.clj
@@ -63,7 +63,7 @@
(deftest superuser-operations-test
(testing "superuser operations require superuser"
(mt/with-premium-features #{:hosting}
- (with-redefs [hm.client/call mock-hm-call]
+ (mt/with-dynamic-fn-redefs [hm.client/call mock-hm-call]
(doseq [op ["mb-plan-trial-up" "mb-plan-trial-up-available"
"mb-plan-change-plan" "mb-plan-change-plan-preview"]]
(testing (str "operation " op " requires superuser")
@@ -71,7 +71,7 @@
(mt/user-http-request :rasta :post 403 (str "ee/cloud-proxy/" op)))))))))
(testing "superuser can access superuser operations"
(mt/with-premium-features #{:hosting}
- (with-redefs [hm.client/call mock-hm-call]
+ (mt/with-dynamic-fn-redefs [hm.client/call mock-hm-call]
(doseq [op ["mb-plan-trial-up" "mb-plan-trial-up-available"
"mb-plan-change-plan" "mb-plan-change-plan-preview"]]
(testing (str "superuser can access " op)
@@ -94,7 +94,7 @@
(deftest response-key-conversion-test
(testing "response keys are converted to snake_case for frontend"
(mt/with-premium-features #{:hosting}
- (with-redefs [hm.client/call mock-hm-call]
+ (mt/with-dynamic-fn-redefs [hm.client/call mock-hm-call]
(let [resp (mt/user-http-request :crowberto :post 200 "ee/cloud-proxy/mb-plan-trial-up-available")]
(is (contains? resp :plan_alias))
(is (not (contains? resp :plan-alias))))
diff --git a/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/cache_test.clj b/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/cache_test.clj
index c17d0495ee4..84352031a48 100644
--- a/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/cache_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/cache_test.clj
@@ -230,7 +230,7 @@
:status :active
:bundle_hash "abc123"
:manifest manifest}]
- (with-redefs [cache/get-asset (fn [_ asset-name] (.getBytes (str "bytes:" asset-name) "UTF-8"))]
+ (mt/with-dynamic-fn-redefs [cache/get-asset (fn [_ asset-name] (.getBytes (str "bytes:" asset-name) "UTF-8"))]
(testing "serves the manifest icon"
(is (= "bytes:icon.svg"
(some-> (cache/resolve-asset plugin "icon.svg") (String. "UTF-8")))))
diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/sync_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/sync_test.clj
index 3ab7627da85..ec069f66de4 100644
--- a/enterprise/backend/test/metabase_enterprise/data_apps/sync_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_apps/sync_test.clj
@@ -54,10 +54,10 @@
(mt/with-model-cleanup [:model/DataApp]
(let [files (merge (app-files "broken" {:name "Broken" :path "index.js" :bundle "BROKEN"})
(app-files "working" {:name "Working" :path "index.js" :bundle "WORKING"}))]
- (with-redefs [data-app.resources/ensure-resources!
- (fn [app]
- (when (= "broken" (:name app))
- (throw (ex-info "Resource provisioning failed." {}))))]
+ (mt/with-dynamic-fn-redefs [data-app.resources/ensure-resources!
+ (fn [app]
+ (when (= "broken" (:name app))
+ (throw (ex-info "Resource provisioning failed." {}))))]
(is (=? {:synced 2 :changed 2}
(data-app.sync/import-from-snapshot! (snapshot files))))
(is (= "Resource provisioning failed."
@@ -321,17 +321,17 @@
(mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
(let [files (merge (app-files "broken" {:name "Broken" :path "index.js" :bundle "OLD"})
(app-files "working" {:name "Working" :path "index.js" :bundle "OLD"}))
- ensure-resources! data-app.resources/ensure-resources!]
+ ensure-resources! (mt/original-fn #'data-app.resources/ensure-resources!)]
(data-app.sync/import-from-snapshot! (snapshot files))
(let [collection-id (t2/select-one-fn :resource_collection_id :model/DataApp :name "broken")
old-name (t2/select-one-fn :name :model/Collection :id collection-id)]
; inject an error into `ensure-resources!` for the "broken" app
- (with-redefs [data-app.resources/ensure-resources!
- (fn [app]
- (ensure-resources! app)
- (when (= "broken" (:name app))
- (t2/update! :model/Collection :id collection-id {:name "Partial update"})
- (throw (ex-info "Resource provisioning failed." {}))))]
+ (mt/with-dynamic-fn-redefs [data-app.resources/ensure-resources!
+ (fn [app]
+ (ensure-resources! app)
+ (when (= "broken" (:name app))
+ (t2/update! :model/Collection :id collection-id {:name "Partial update"})
+ (throw (ex-info "Resource provisioning failed." {}))))]
(data-app.sync/import-from-snapshot!
(snapshot (assoc files "data_apps/broken/index.js" "NEW" "data_apps/working/index.js" "NEW"))))
; the "broken" app bundle with sync error should be rolled back to "OLD"
@@ -348,13 +348,13 @@
(mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]
(let [working-files (app-files "working" {:name "Working" :path "index.js" :bundle "OLD"})
files (merge working-files (app-files "removed" {:name "Removed" :path "index.js" :bundle "OLD"}))
- prune! data-apps.db/delete-data-apps-not-named!]
+ prune! (mt/original-fn #'data-apps.db/delete-data-apps-not-named!)]
(data-app.sync/import-from-snapshot! (snapshot files))
; inject an error into deleting data apps
- (with-redefs [data-apps.db/delete-data-apps-not-named!
- (fn [slugs]
- (prune! slugs)
- (throw (ex-info "Pruning failed." {})))]
+ (mt/with-dynamic-fn-redefs [data-apps.db/delete-data-apps-not-named!
+ (fn [slugs]
+ (prune! slugs)
+ (throw (ex-info "Pruning failed." {})))]
; sync should report the error from pruning step
(is (=? {:synced 1 :changed 1 :removed 0 :pruning-error "Pruning failed."}
(data-app.sync/sync-from-snapshot!
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/findings_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/findings_test.clj
index 52a4ed7ec1d..96800f89922 100644
--- a/enterprise/backend/test/metabase_enterprise/dependencies/findings_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/findings_test.clj
@@ -372,12 +372,12 @@
(mt/with-temp [:model/Card {card1-id :id} {:dataset_query (native-card "select id from orders")}
:model/Card {card2-id :id} {:dataset_query (native-card "select id from products")}]
(let [wanted #{card1-id card2-id}
- upsert-analysis! deps.findings/upsert-analysis!]
- (with-redefs [deps.findings/upsert-analysis!
- (fn [instance]
- (when (wanted (:id instance))
- (swap! providers conj (:lib/metadata (:dataset_query instance))))
- (upsert-analysis! instance))]
+ upsert-analysis! (mt/original-fn #'deps.findings/upsert-analysis!)]
+ (mt/with-dynamic-fn-redefs [deps.findings/upsert-analysis!
+ (fn [instance]
+ (when (wanted (:id instance))
+ (swap! providers conj (:lib/metadata (:dataset_query instance))))
+ (upsert-analysis! instance))]
(deps.findings/analyze-batch! :card 500)))
(testing "both cards were selected, so the assertion below is meaningful"
(is (= 2 (count @providers))))
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/task/backfill_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/task/backfill_test.clj
index f39e7195b79..5fc75181057 100644
--- a/enterprise/backend/test/metabase_enterprise/dependencies/task/backfill_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/task/backfill_test.clj
@@ -226,6 +226,9 @@
(testing "Scheduling new runs while the backfill job is executing keeps the trigger count ≤ 1"
(let [job-started (promise)
can-finish (promise)]
+ ;; the job body runs on a Quartz worker thread, which does not inherit *local-redefs* —
+ ;; only a root swap is visible there
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [dependencies.backfill/backfill-dependencies!
(fn []
(deliver job-started true)
@@ -502,18 +505,18 @@
which is what exhausted the heap on instances with large warehouses."
(backfill-all-existing-entities!)
(let [providers (atom [])
- calculate-deps deps.calculation/calculate-deps
+ calculate-deps (mt/original-fn #'deps.calculation/calculate-deps)
native-card (fn [sql] {:database (mt/id) :type :native :native {:query sql}})]
(mt/with-premium-features #{}
(mt/with-temp [:model/Card {card1-id :id} {:dataset_query (native-card "select id from orders")}
:model/Card {card2-id :id} {:dataset_query (native-card "select id from products")}]
(mark-stale! :card card1-id)
(mark-stale! :card card2-id)
- (with-redefs [deps.calculation/calculate-deps
- (fn [entity-type entity]
- (when-let [mp (:lib/metadata (:dataset_query entity))]
- (swap! providers conj mp))
- (calculate-deps entity-type entity))]
+ (mt/with-dynamic-fn-redefs [deps.calculation/calculate-deps
+ (fn [entity-type entity]
+ (when-let [mp (:lib/metadata (:dataset_query entity))]
+ (swap! providers conj mp))
+ (calculate-deps entity-type entity))]
(backfill-dependencies-single-trigger!))
(testing "both cards were analyzed, so the assertion below is meaningful"
(is (<= 2 (count @providers))))
@@ -531,7 +534,7 @@
(mt/with-premium-features #{}
(mt/with-temp [:model/Card {card-id :id} {:dataset_query (mt/mbql-query orders)}]
(mark-stale! :card card-id)
- (with-redefs [deps.calculation/calculate-deps (fn [& _] (throw (Error. "simulated fatal error")))]
+ (mt/with-dynamic-fn-redefs [deps.calculation/calculate-deps (fn [& _] (throw (Error. "simulated fatal error")))]
(testing "the Error propagates instead of being swallowed, failing the job"
(is (thrown-with-msg? Error #"simulated fatal error"
(backfill-dependencies-single-trigger!)))))
@@ -582,7 +585,7 @@
(mt/with-temp [:model/Card {card-id :id} {:dataset_query (mt/mbql-query orders)}]
(is (not (t2/exists? :model/DependencyStatus :entity_type :card :entity_id card-id))
"test setup: the card must have no status row, which is what makes it eligible")
- (with-redefs [deps.calculation/calculate-deps (fn [& _] (throw (ex-info "boom" {})))]
+ (mt/with-dynamic-fn-redefs [deps.calculation/calculate-deps (fn [& _] (throw (ex-info "boom" {})))]
(backfill-dependencies-single-trigger!))
(testing "the failure is recorded, so the entity backs off instead of being reselected unchanged"
(let [{:keys [fail_count next_retry_at]}
diff --git a/enterprise/backend/test/metabase_enterprise/entity_retrieval/core_test.clj b/enterprise/backend/test/metabase_enterprise/entity_retrieval/core_test.clj
index 86bbfae6c1a..a8ae34519e7 100644
--- a/enterprise/backend/test/metabase_enterprise/entity_retrieval/core_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/entity_retrieval/core_test.clj
@@ -80,14 +80,14 @@
(deftest search-skips-embedding-for-an-incompatible-index-test
(mt/with-premium-features #{:library-retrieval}
- (with-redefs [entity-retrieval.core/available? (constantly true)
- semantic.db.datasource/ensure-initialized-data-source! (constantly ::datasource)
- semantic.embedding/get-configured-model (constantly semantic.tu/mock-embedding-model)
- index-table/index-status (constantly :incompatible)
- semantic.embedding/get-embedding (fn [& _]
- (throw (ex-info "must not embed" {})))
- reconcile/with-index-read-lock (fn [_ds f]
- (f ::locked-connection))]
+ (mt/with-dynamic-fn-redefs [entity-retrieval.core/available? (constantly true)
+ semantic.db.datasource/ensure-initialized-data-source! (constantly ::datasource)
+ semantic.embedding/get-configured-model (constantly semantic.tu/mock-embedding-model)
+ index-table/index-status (constantly :incompatible)
+ semantic.embedding/get-embedding (fn [& _]
+ (throw (ex-info "must not embed" {})))
+ reconcile/with-index-read-lock (fn [_ds f]
+ (f ::locked-connection))]
#_{:clj-kondo/ignore [:discouraged-var]}
(is (= [] (entity-retrieval.core/search-unfiltered "the query" 10))))))
diff --git a/enterprise/backend/test/metabase_enterprise/gsheets/api_test.clj b/enterprise/backend/test/metabase_enterprise/gsheets/api_test.clj
index 1c4497276e6..5aa74a612d5 100644
--- a/enterprise/backend/test/metabase_enterprise/gsheets/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/gsheets/api_test.clj
@@ -69,7 +69,7 @@
(deftest gsheets-calls-pass-when-activated-and-superuser
(mt/with-premium-features #{:etl-connections :attached-dwh :hosting}
(mt/with-temporary-setting-values [api-key "non-blank"]
- (with-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
+ (mt/with-dynamic-fn-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
(is (malli=
[:map [:email [:maybe :string]]]
(mt/user-http-request :crowberto :get 200 "ee/gsheets/service-account")))))))
@@ -141,7 +141,7 @@
(with-sample-db-as-dwh
(mt/with-premium-features #{:etl-connections :attached-dwh :hosting}
(mt/with-temporary-setting-values [gsheets nil]
- (with-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
+ (mt/with-dynamic-fn-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
(let [result (mt/user-http-request :crowberto :post 200 "ee/gsheets/connection" {:url gdrive-link})]
(is (partial=
{:status "syncing", :url gdrive-link, :created_by_id (mt/user->id :crowberto)}
@@ -156,7 +156,7 @@
(deftest create-sheet-test
(with-sample-db-as-dwh
(mt/with-premium-features #{:etl-connections :attached-dwh :hosting}
- (with-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
+ (mt/with-dynamic-fn-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
(is (partial=
{:status "syncing", :url sheet-link}
(mt/user-http-request :crowberto :post 200 "ee/gsheets/connection" {:url sheet-link})))))))
@@ -165,7 +165,7 @@
(with-sample-db-as-dwh
(mt/with-premium-features #{:etl-connections :attached-dwh :hosting}
(mt/with-temporary-setting-values [gsheets nil]
- (with-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
+ (mt/with-dynamic-fn-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
(let [result (mt/user-http-request :crowberto :post 502 "ee/gsheets/connection" {:url gsheet-error-link})]
(is (partial=
{:message "Unable to setup drive folder sync.\nPlease check that the folder is shared with the proper service account email and sharing permissions."
@@ -181,7 +181,7 @@
(deftest folder-syncing-test
(mt/with-premium-features #{:etl-connections :attached-dwh :hosting}
(testing "Sync starts"
- (with-redefs [hm.client/make-request (partial mock-make-request (+syncing happy-responses))]
+ (mt/with-dynamic-fn-redefs [hm.client/make-request (partial mock-make-request (+syncing happy-responses))]
(mt/with-temporary-setting-values [gsheets {:url "stored-url" :created-by-id 2 :gdrive/conn-id gdrive-syncing-link}]
(let [response (mt/user-http-request :crowberto :post 200 "ee/gsheets/connection/sync")]
(is (partial= {:status "syncing", :url "stored-url", :created_by_id 2}
@@ -203,12 +203,12 @@
(mt/with-premium-features #{:etl-connections :attached-dwh :hosting}
(testing "when no config exists, return not-connected"
(mt/with-temporary-setting-values [gsheets nil]
- (with-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
+ (mt/with-dynamic-fn-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
(let [response (mt/user-http-request :crowberto :get 200 "ee/gsheets/connection")]
(is (= {:status "not-connected"} response))))))
(testing "when state==initializing, status==initializing"
(mt/with-temporary-setting-values [gsheets (assoc mock-gsheet :gdrive/conn-id gdrive-initializing-link)]
- (with-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
+ (mt/with-dynamic-fn-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
(let [response (mt/user-http-request :crowberto :get 200 "ee/gsheets/connection")]
(is (partial= {:status "initializing", :url "test-url" :created_by_id 2}
response))
@@ -220,7 +220,7 @@
(is (nil? (:sync_started_at (gsheets)))))))))
(testing "when state==active with last-sync-started-at after last-sync-at, status==syncing"
(mt/with-temporary-setting-values [gsheets (assoc mock-gsheet :gdrive/conn-id gdrive-syncing-link)]
- (with-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
+ (mt/with-dynamic-fn-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
(let [response (mt/user-http-request :crowberto :get 200 "ee/gsheets/connection")]
(is (partial= {:status "syncing", :url "test-url" :created_by_id 2}
response))
@@ -232,7 +232,7 @@
(is (nil? (:sync_started_at (gsheets)))))))))
(testing "when state==active, status==active"
(mt/with-temporary-setting-values [gsheets (assoc mock-gsheet :gdrive/conn-id gdrive-active-link)]
- (with-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
+ (mt/with-dynamic-fn-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
(let [response (mt/user-http-request :crowberto :get 200 "ee/gsheets/connection")]
(is (partial= {:status "active", :url "test-url" :created_by_id 2}
response))
@@ -246,7 +246,7 @@
(is (nil? (:last_sync_at (gsheets)))))))))
(testing "when paused"
(mt/with-temporary-setting-values [gsheets (assoc mock-gsheet :gdrive/conn-id gdrive-paused-link)]
- (with-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
+ (mt/with-dynamic-fn-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
(let [response (mt/user-http-request :crowberto :get 200 "ee/gsheets/connection")]
(is (partial= {:status "error",
:url "test-url"
@@ -265,24 +265,24 @@
(is (nil? (:last_sync_at (gsheets)))))))))
(testing "when paused and no last sync"
(mt/with-temporary-setting-values [gsheets (assoc mock-gsheet :gdrive/conn-id "never-synced")]
- (with-redefs [hm.client/make-request (partial mock-make-request
- (assoc happy-responses
- {:method :get, :url "/api/v2/mb/connections/never-synced", :body nil}
- [:ok
- {:status 200,
- :body {:last-sync-started-at nil
- :hosted-instance-resource-id 15378,
- :last-sync-at nil
- :type "gdrive"
- :status-reason "DWH quota exceeded."
- :updated-at "2025-05-29T14:36:26Z"
- :hosted-instance-id "c6633c12-8ed2-4e74-ba7f-3602791d252c"
- :status "paused"
- :id "7346e101-fa51-4f1a-9655-810aaea63fe4"
- :error nil
- :sync-callback-token nil
- :created-at "2025-05-29T14:36:25Z"
- :error-detail nil}}]))]
+ (mt/with-dynamic-fn-redefs [hm.client/make-request (partial mock-make-request
+ (assoc happy-responses
+ {:method :get, :url "/api/v2/mb/connections/never-synced", :body nil}
+ [:ok
+ {:status 200,
+ :body {:last-sync-started-at nil
+ :hosted-instance-resource-id 15378,
+ :last-sync-at nil
+ :type "gdrive"
+ :status-reason "DWH quota exceeded."
+ :updated-at "2025-05-29T14:36:26Z"
+ :hosted-instance-id "c6633c12-8ed2-4e74-ba7f-3602791d252c"
+ :status "paused"
+ :id "7346e101-fa51-4f1a-9655-810aaea63fe4"
+ :error nil
+ :sync-callback-token nil
+ :created-at "2025-05-29T14:36:25Z"
+ :error-detail nil}}]))]
(let [response (mt/user-http-request :crowberto :get 200 "ee/gsheets/connection")]
(is (partial= {:status "error", :url "test-url" :created_by_id 2 :error_message "DWH quota exceeded."}
response))
@@ -295,7 +295,7 @@
(is (nil? (:last_sync_at (gsheets)))))))))
(testing "when 400 error response"
(mt/with-temporary-setting-values [gsheets (assoc mock-gsheet :gdrive/conn-id gdrive-400-error-link)]
- (with-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
+ (mt/with-dynamic-fn-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
(let [response (mt/user-http-request :crowberto :get 200 "ee/gsheets/connection")]
(is (partial= {:status "error"
:url "test-url"
@@ -308,7 +308,7 @@
(is (pos-int? (:db_id response)))))))
(testing "when 200 error response"
(mt/with-temporary-setting-values [gsheets (assoc mock-gsheet :gdrive/conn-id gdrive-200-error-link)]
- (with-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
+ (mt/with-dynamic-fn-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
(let [response (mt/user-http-request :crowberto :get 200 "ee/gsheets/connection")]
(is (partial= {:status "error", :url "test-url" :created_by_id 2} response))
(is (pos-int? (:db_id response)))))))))))
@@ -322,17 +322,17 @@
(mt/with-premium-features #{:etl-connections :attached-dwh :hosting}
(testing "when the connection does not exist, it is deleted"
(mt/with-temporary-setting-values [gsheets (assoc mock-gsheet :gdrive/conn-id gdrive-403-error-link)]
- (with-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
+ (mt/with-dynamic-fn-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
(let [response (mt/user-http-request :crowberto :get 200 "ee/gsheets/connection")]
(is (= {:status "not-connected"} response))
(is (= {} (gsheets)))))))
(testing "when the HM gives a 403 response for the connection, but it shows in the connection list then it is not deleted"
(mt/with-temporary-setting-values [gsheets (assoc mock-gsheet :gdrive/conn-id gdrive-active-link)]
- (with-redefs [hm.client/make-request (partial mock-make-request (assoc happy-responses
- {:method :get, :url (str "/api/v2/mb/connections/" gdrive-active-link), :body nil}
- [:error
- {:status 403,
- :body {:error "User not authorized to act over resource."}}]))]
+ (mt/with-dynamic-fn-redefs [hm.client/make-request (partial mock-make-request (assoc happy-responses
+ {:method :get, :url (str "/api/v2/mb/connections/" gdrive-active-link), :body nil}
+ [:error
+ {:status 403,
+ :body {:error "User not authorized to act over resource."}}]))]
(let [response (mt/user-http-request :crowberto :get 200 "ee/gsheets/connection")]
(is (partial= {:status "error"
:error_message "Unable to check Google Drive connection. Reconnect if the issue persists."
@@ -341,12 +341,12 @@
(is (= 15 (:created-at (gsheets))))))))
(testing "when the HM gives a 403 response for the connection, and the connection list fails, then it is not deleted"
(mt/with-temporary-setting-values [gsheets (assoc mock-gsheet :gdrive/conn-id gdrive-403-error-link)]
- (with-redefs [hm.client/make-request (partial mock-make-request
- (assoc happy-responses
- {:method :get, :url "/api/v2/mb/connections", :body nil}
- [:error
- {:status 403,
- :body {:error "User not authorized to act over resource."}}]))]
+ (mt/with-dynamic-fn-redefs [hm.client/make-request (partial mock-make-request
+ (assoc happy-responses
+ {:method :get, :url "/api/v2/mb/connections", :body nil}
+ [:error
+ {:status 403,
+ :body {:error "User not authorized to act over resource."}}]))]
(let [response (mt/user-http-request :crowberto :get 200 "ee/gsheets/connection")]
(is (= "error" (:status response)))
(is (= 15 (:created-at (gsheets))))))))))))
@@ -355,7 +355,7 @@
(with-sample-db-as-dwh
(mt/with-premium-features #{:etl-connections :attached-dwh :hosting}
(mt/with-temporary-setting-values [gsheets {:url "stored-url" :created-by-id 2}]
- (with-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
+ (mt/with-dynamic-fn-redefs [hm.client/make-request (partial mock-make-request happy-responses)]
(is (= {:status "not-connected"}
(mt/user-http-request :crowberto :delete 200 "ee/gsheets/connection")))
(is (empty? (gsheets))))))))
@@ -368,7 +368,7 @@
(deftest delete-folder-cannot-find
(with-sample-db-as-dwh
(mt/with-premium-features #{:etl-connections :attached-dwh :hosting}
- (with-redefs [hm.client/make-request (partial mock-make-request (+empty-conn-listing happy-responses))]
+ (mt/with-dynamic-fn-redefs [hm.client/make-request (partial mock-make-request (+empty-conn-listing happy-responses))]
(is (= {:status "not-connected"}
(mt/user-http-request :crowberto :delete 200 "ee/gsheets/connection")))))))
@@ -380,7 +380,7 @@
(deftest delete-folder-fail
(with-sample-db-as-dwh
(mt/with-premium-features #{:etl-connections :attached-dwh :hosting}
- (with-redefs [hm.client/make-request (partial mock-make-request (+failed-delete-response happy-responses))]
+ (mt/with-dynamic-fn-redefs [hm.client/make-request (partial mock-make-request (+failed-delete-response happy-responses))]
(= {:status "not-connected"}
(mt/user-http-request :crowberto :delete 200 "ee/gsheets/connection"))))))
diff --git a/enterprise/backend/test/metabase_enterprise/harbormaster/client_test.clj b/enterprise/backend/test/metabase_enterprise/harbormaster/client_test.clj
index b7594c7a5cc..56411afa8c9 100644
--- a/enterprise/backend/test/metabase_enterprise/harbormaster/client_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/harbormaster/client_test.clj
@@ -27,11 +27,11 @@
;; mt/with-temporary-setting-values is not used here because we want to test the behavior of the function when the
;; api-key is blank or nil, and mt/with-temporary-setting-values will not allow us to set the api-key to blank
;; or nil.
- (with-redefs [metabase.settings.models.setting/get-raw-value (+value-for-setting grv :api-key "")]
+ (mt/with-dynamic-fn-redefs [metabase.settings.models.setting/get-raw-value (+value-for-setting grv :api-key "")]
(is (thrown-with-msg? Exception
#"Missing api-key."
(#'hm.client/->config))))
- (with-redefs [metabase.settings.models.setting/get-raw-value (+value-for-setting grv :api-key nil)]
+ (mt/with-dynamic-fn-redefs [metabase.settings.models.setting/get-raw-value (+value-for-setting grv :api-key nil)]
(is (thrown-with-msg? Exception
#"Missing api-key."
(#'hm.client/->config))))))
diff --git a/enterprise/backend/test/metabase_enterprise/internal_stats/metabot_test.clj b/enterprise/backend/test/metabase_enterprise/internal_stats/metabot_test.clj
index 87b20d361d3..ddf9181a439 100644
--- a/enterprise/backend/test/metabase_enterprise/internal_stats/metabot_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/internal_stats/metabot_test.clj
@@ -40,11 +40,11 @@
:model model
:usage {:promptTokens prompt-tokens :completionTokens completion-tokens}
:id message-id}]))]
- (with-redefs [openrouter/openrouter mock-fn
- claude/claude mock-fn
- openai/openai mock-fn
- ;; skip title generation to avoid second llm call + ai_usage_log row
- conversation-title/ensure-title! (constantly {:status :missing})]
+ (mt/with-dynamic-fn-redefs [openrouter/openrouter mock-fn
+ claude/claude mock-fn
+ openai/openai mock-fn
+ ;; skip title generation to avoid second llm call + ai_usage_log row
+ conversation-title/ensure-title! (constantly {:status :missing})]
(mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
{:message message
:context {}
@@ -343,9 +343,9 @@
:model model
:usage {:promptTokens prompt-tokens :completionTokens completion-tokens}
:id "msg-eqg"}]))]
- (with-redefs [openrouter/openrouter mock-fn
- claude/claude mock-fn
- openai/openai mock-fn]
+ (mt/with-dynamic-fn-redefs [openrouter/openrouter mock-fn
+ claude/claude mock-fn
+ openai/openai mock-fn]
(eqg/generate-example-questions {:tables tables :metrics []}))))
(defn- max-usage-log-id
diff --git a/enterprise/backend/test/metabase_enterprise/library/validation_test.clj b/enterprise/backend/test/metabase_enterprise/library/validation_test.clj
index 7392c23b0fa..9ee05b0f395 100644
--- a/enterprise/backend/test/metabase_enterprise/library/validation_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/library/validation_test.clj
@@ -91,7 +91,7 @@
(mt/with-temp [:model/Collection library {:name "Test Library" :type collection/library-collection-type}
:model/Collection models {:name "Test Semantic Model Layer" :type collection/library-data-collection-type}
:model/Collection metrics {:name "Test Semantic Metrics Layer" :type collection/library-metrics-collection-type}]
- (with-redefs [collection/library-root-collection? (constantly true)]
+ (mt/with-dynamic-fn-redefs [collection/library-root-collection? (constantly true)]
(doseq [col [library models metrics]]
(testing (str "Checking type " (:type col))
(is (thrown-with-msg? clojure.lang.ExceptionInfo
@@ -196,9 +196,9 @@
:location (str "/" (:id library-root) "/" (:id metrics-root) "/")}
:model/Collection vanilla {:name "Vanilla Collection" :type nil}]
(let [vanilla-location (str "/" (:id vanilla) "/")]
- (with-redefs [collection/library-root-collection? (fn [coll]
- (contains? #{(:id library-root) (:id data-root) (:id metrics-root)}
- (:id coll)))]
+ (mt/with-dynamic-fn-redefs [collection/library-root-collection? (fn [coll]
+ (contains? #{(:id library-root) (:id data-root) (:id metrics-root)}
+ (:id coll)))]
(testing "Cannot move the Library collection itself into a vanilla collection"
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Cannot update properties on a Library collection"
(t2/update! :model/Collection (:id library-root) {:location vanilla-location}))))
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj
index 664b2823c8d..88f94d2b5c9 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj
@@ -69,9 +69,9 @@
remote-sync-token "valid-token"
remote-sync-branch "main"
remote-sync-type :read-only]
- (with-redefs [settings/check-git-settings! (constantly nil)
- source.git/git-source (fn [_ _ _ _] {:fake-source true})
- source.git/branches (fn [_] ["main"])]
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (constantly nil)
+ source.git/git-source (fn [_ _ _ _] {:fake-source true})
+ source.git/branches (fn [_] ["main"])]
(is (= {:status "success"}
(mt/user-http-request :crowberto :post 200 "ee/remote-sync/test-connection" {})))))))
@@ -85,9 +85,9 @@
remote-sync-token "valid-token"
remote-sync-branch ""
remote-sync-type :read-write]
- (with-redefs [settings/check-git-settings! (constantly nil)
- source.git/git-source (fn [_ _ _ _] {:fake-source true})
- source.git/branches (fn [_] (swap! branches-calls inc) [])]
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (constantly nil)
+ source.git/git-source (fn [_ _ _ _] {:fake-source true})
+ source.git/branches (fn [_] (swap! branches-calls inc) [])]
(mt/user-http-request :crowberto :post 200 "ee/remote-sync/test-connection" {})
(is (= 1 @branches-calls)
"Test Connection must call git/branches even when check-git-settings! skips the remote check"))))))
@@ -98,9 +98,9 @@
remote-sync-token "rotated-token"
remote-sync-branch ""
remote-sync-type :read-write]
- (with-redefs [settings/check-git-settings! (constantly nil)
- source.git/git-source (fn [_ _ _ _] {:fake-source true})
- source.git/branches (fn [_] (throw (ex-info "Authentication failed" {})))]
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (constantly nil)
+ source.git/git-source (fn [_ _ _ _] {:fake-source true})
+ source.git/branches (fn [_] (throw (ex-info "Authentication failed" {})))]
(is (= "Authentication failed: Please check your git credentials"
(mt/user-http-request :crowberto :post 400 "ee/remote-sync/test-connection" {})))))))
@@ -111,11 +111,11 @@
remote-sync-token "saved-token"
remote-sync-branch "main"
remote-sync-type :read-only]
- (with-redefs [settings/check-git-settings! (constantly nil)
- source.git/git-source (fn [url _ token _]
- (reset! captured {:url url :token token})
- {:fake-source true})
- source.git/branches (fn [_] [])]
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (constantly nil)
+ source.git/git-source (fn [url _ token _]
+ (reset! captured {:url url :token token})
+ {:fake-source true})
+ source.git/branches (fn [_] [])]
(mt/user-http-request :crowberto :post 200 "ee/remote-sync/test-connection"
{:remote-sync-url "https://github.com/other/repo.git"
:remote-sync-token "new-token"})
@@ -129,11 +129,11 @@
remote-sync-token full-token
remote-sync-branch "main"
remote-sync-type :read-only]
- (with-redefs [settings/check-git-settings! (constantly nil)
- source.git/git-source (fn [_ _ token _]
- (reset! captured token)
- {:fake-source true})
- source.git/branches (fn [_] [])]
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (constantly nil)
+ source.git/git-source (fn [_ _ token _]
+ (reset! captured token)
+ {:fake-source true})
+ source.git/branches (fn [_] [])]
(mt/user-http-request :crowberto :post 200 "ee/remote-sync/test-connection"
{:remote-sync-token (setting/obfuscate-value full-token)})
(is (= full-token @captured)
@@ -158,11 +158,11 @@
remote-sync-branch "main"
remote-sync-type :read-only]
(testing "Authentication failure maps to credentials error"
- (with-redefs [settings/check-git-settings! (fn [_] (throw (ex-info "Authentication failed" {})))]
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (fn [_] (throw (ex-info "Authentication failed" {})))]
(is (= "Authentication failed: Please check your git credentials"
(mt/user-http-request :crowberto :post 400 "ee/remote-sync/test-connection" {})))))
(testing "Repository-not-found maps to URL error"
- (with-redefs [settings/check-git-settings! (fn [_] (throw (ex-info "Repository not found" {})))]
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (fn [_] (throw (ex-info "Repository not found" {})))]
(is (= "Repository not found: Please check the repository URL"
(mt/user-http-request :crowberto :post 400 "ee/remote-sync/test-connection" {}))))))))
@@ -1070,7 +1070,7 @@
:started_at (t/offset-date-time)
:progress 0.0}]
(let [check-git-call-count (atom 0)]
- (with-redefs [settings/check-git-settings! (fn [_] (swap! check-git-call-count inc) true)]
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (fn [_] (swap! check-git-call-count inc) true)]
(mt/with-temporary-setting-values [remote-sync-url "file://my/repo.git"
remote-sync-token nil
remote-sync-type :read-only
@@ -1746,9 +1746,9 @@
(testing "PUT /api/ee/remote-sync/settings does not mark collections as synced when settings validation fails"
(mt/with-temporary-setting-values [remote-sync-type :read-write]
(mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :location "/" :is_remote_synced false}]
- (with-redefs [settings/check-and-update-remote-settings!
- (fn [_] (throw (ex-info "Authentication is required" {:status-code 400})))
- impl/finish-remote-config! (constantly nil)]
+ (mt/with-dynamic-fn-redefs [settings/check-and-update-remote-settings!
+ (fn [_] (throw (ex-info "Authentication is required" {:status-code 400})))
+ impl/finish-remote-config! (constantly nil)]
(mt/user-http-request :crowberto :put 400 "ee/remote-sync/settings"
{:remote-sync-url "https://github.com/test/private-repo.git"
:remote-sync-type :read-write
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/core_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/core_test.clj
index 2345b5d9a21..6a93c8e9480 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/core_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/core_test.clj
@@ -565,7 +565,7 @@
(mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection"
:location "/"
:is_remote_synced false}]
- (with-redefs [guards/task-running? (constantly true)]
+ (mt/with-dynamic-fn-redefs [guards/task-running? (constantly true)]
(is (thrown-with-msg? Exception #"Remote sync task in progress"
(core/bulk-set-remote-sync {coll-id true})))
(is (false? (:is_remote_synced (t2/select-one :model/Collection :id coll-id)))
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/impl_progress_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/impl_progress_test.clj
index 8ae8cd4e496..f807462927d 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/impl_progress_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/impl_progress_test.clj
@@ -3,7 +3,8 @@
(:require
[clojure.test :refer :all]
[metabase-enterprise.remote-sync.impl :as impl]
- [metabase-enterprise.remote-sync.source.protocol :as source.p]))
+ [metabase-enterprise.remote-sync.source.protocol :as source.p]
+ [metabase.test :as mt]))
(set! *warn-on-reflection* true)
@@ -19,10 +20,10 @@
(deftest stage-writes-invokes-on-chunk-with-cumulative-count-test
(testing "stage-writes calls on-chunk once per chunk with the running staged count, and stages everything"
- (with-redefs [;; make each row its own chunk (matching the real {:model_type :rows} chunk shape) and a
- ;; trivial entity, so we exercise the loop deterministically without hitting serdes/the app DB
- impl/->sized-chunks (fn [rows] (map (fn [row] {:model_type (:model_type row) :rows [row]}) rows))
- impl/extract-chunk (fn [{:keys [rows]}] (map (fn [row] [row {:e (:model_id row)}]) rows))]
+ (mt/with-dynamic-fn-redefs [;; make each row its own chunk (matching the real {:model_type :rows} chunk shape) and a
+ ;; trivial entity, so we exercise the loop deterministically without hitting serdes/the app DB
+ impl/->sized-chunks (fn [rows] (map (fn [row] {:model_type (:model_type row) :rows [row]}) rows))
+ impl/extract-chunk (fn [{:keys [rows]}] (map (fn [row] [row {:e (:model_id row)}]) rows))]
(let [staged (atom [])
commit (->RecordingCommit staged)
rows [{:model_type "card" :model_id 1 :file_path "a"}
@@ -44,7 +45,7 @@
(finish-commit! [_ _message] "sha")
(finish-commit! [_ _message report] (when report (report 0.8 {:force? true})) "sha")
(abort-commit! [_] nil))]
- (with-redefs [source.p/open-commit (fn [_] commit)]
+ (mt/with-dynamic-fn-redefs [source.p/open-commit (fn [_] commit)]
(#'impl/commit-staged! {:managed-dirs []} "msg"
(fn [_c] [{:id 1}])
(fn [f & _] (swap! reported conj f))))
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj
index 0ca5f762544..210d65e980a 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj
@@ -1692,8 +1692,8 @@ serdes/meta:
remote-sync-token "token"
remote-sync-branch "main"
remote-sync-type :read-write]
- (with-redefs [guards/task-running? (constantly true)
- source/source-from-settings (fn [& _] (test-helpers/create-mock-source))]
+ (mt/with-dynamic-fn-redefs [guards/task-running? (constantly true)
+ source/source-from-settings (fn [& _] (test-helpers/create-mock-source))]
(is (thrown-with-msg? Exception #"Remote sync task in progress"
(impl/async-import! "main" true {})))
(is (zero? (t2/count :model/RemoteSyncTask))
@@ -1707,8 +1707,8 @@ serdes/meta:
remote-sync-token "token"
remote-sync-branch "main"
remote-sync-type :read-write]
- (with-redefs [guards/task-running? (constantly true)
- source/source-from-settings (fn [& _] (test-helpers/create-mock-source))]
+ (mt/with-dynamic-fn-redefs [guards/task-running? (constantly true)
+ source/source-from-settings (fn [& _] (test-helpers/create-mock-source))]
(is (thrown-with-msg? Exception #"Remote sync task in progress"
(impl/async-export! "main" true "msg")))
(is (zero? (t2/count :model/RemoteSyncTask))
@@ -1724,8 +1724,8 @@ serdes/meta:
remote-sync-type :read-write]
(let [mock-source (test-helpers/create-mock-source)
initial-branches @(:branches-atom mock-source)]
- (with-redefs [guards/task-running? (constantly true)
- source/source-from-settings (fn [& _] mock-source)]
+ (mt/with-dynamic-fn-redefs [guards/task-running? (constantly true)
+ source/source-from-settings (fn [& _] mock-source)]
(is (thrown-with-msg? Exception #"Remote sync task in progress"
(impl/create-branch! "feature-x" "main")))
(is (= "main" (remote-sync.settings/remote-sync-branch))
@@ -1743,8 +1743,8 @@ serdes/meta:
remote-sync-type :read-write]
(let [mock-source (test-helpers/create-mock-source)
initial-branches @(:branches-atom mock-source)]
- (with-redefs [guards/task-running? (constantly true)
- source/source-from-settings (fn [& _] mock-source)]
+ (mt/with-dynamic-fn-redefs [guards/task-running? (constantly true)
+ source/source-from-settings (fn [& _] mock-source)]
(is (thrown-with-msg? Exception #"Remote sync task in progress"
(impl/stash! "stash-branch" "stash message")))
(is (= "main" (remote-sync.settings/remote-sync-branch))
@@ -1853,15 +1853,15 @@ serdes/meta:
(testing "when the remote advanced and the merge is clean, export! merges, advances the version, and reconciles local"
(mt/with-temp [:model/RemoteSyncTask {task-id :id} {:sync_task_type "export"}]
(let [reconciled (atom nil)]
- (with-redefs [remote-sync.task/last-version (constantly "base-B")
- spec/extract-entities-for-export (constantly [{:dummy true}])
- source/compute-merge (fn [_ _ _ _]
- {:merged [{:path "collections/x.yaml" :content "x"}]
- :conflicts []
- :summary {:added 2 :updated 1 :removed 0}})
- impl/load-snapshot! (fn [snap _ _ & {:keys [finalize!]}]
- (reset! reconciled (source.p/version snap))
- (when finalize! (finalize!)))]
+ (mt/with-dynamic-fn-redefs [remote-sync.task/last-version (constantly "base-B")
+ spec/extract-entities-for-export (constantly [{:dummy true}])
+ source/compute-merge (fn [_ _ _ _]
+ {:merged [{:path "collections/x.yaml" :content "x"}]
+ :conflicts []
+ :summary {:added 2 :updated 1 :removed 0}})
+ impl/load-snapshot! (fn [snap _ _ & {:keys [finalize!]}]
+ (reset! reconciled (source.p/version snap))
+ (when finalize! (finalize!)))]
(let [result (impl/export! (export-test-snapshot "remote-R") task-id "msg"
:merge? true
:source (export-test-source)
@@ -1876,15 +1876,15 @@ serdes/meta:
(testing "when the merge matches the remote tip (nothing to push), export! folds in remote changes, reports a pull, and advances to the tip"
(mt/with-temp [:model/RemoteSyncTask {task-id :id} {:sync_task_type "export"}]
(let [reconciled (atom nil)]
- (with-redefs [remote-sync.task/last-version (constantly "base-B")
- spec/extract-entities-for-export (constantly [{:dummy true}])
- source/compute-merge (fn [_ _ _ _]
- {:merged [{:path "collections/x.yaml" :content "x"}]
- :conflicts []
- :summary {:added 1 :updated 0 :removed 0}})
- impl/load-snapshot! (fn [snap _ _ & {:keys [finalize!]}]
- (reset! reconciled (source.p/version snap))
- (when finalize! (finalize!)))]
+ (mt/with-dynamic-fn-redefs [remote-sync.task/last-version (constantly "base-B")
+ spec/extract-entities-for-export (constantly [{:dummy true}])
+ source/compute-merge (fn [_ _ _ _]
+ {:merged [{:path "collections/x.yaml" :content "x"}]
+ :conflicts []
+ :summary {:added 1 :updated 0 :removed 0}})
+ impl/load-snapshot! (fn [snap _ _ & {:keys [finalize!]}]
+ (reset! reconciled (source.p/version snap))
+ (when finalize! (finalize!)))]
;; the remote-tip snapshot reports the staged tree as identical (empty-commit? true), so the merge
;; pushes no commit
(let [result (impl/export! (export-test-snapshot "remote-R" true) task-id "msg"
@@ -1903,15 +1903,15 @@ serdes/meta:
(testing "when the same entity changed on both sides, export! returns :conflict without advancing the version or reconciling"
(mt/with-temp [:model/RemoteSyncTask {task-id :id} {:sync_task_type "export"}]
(let [reconciled? (atom false)]
- (with-redefs [remote-sync.task/last-version (constantly "base-B")
- spec/extract-entities-for-export (constantly [{:dummy true}])
- source/compute-merge (fn [_ _ _ _]
- {:merged []
- :conflicts [{:key [["Card" "A"]]
- :ours {:path "collections/a.yaml" :content "x"}
- :theirs {:path "collections/a.yaml" :content "y"}}]
- :summary {:added 0 :updated 0 :removed 0}})
- impl/load-snapshot! (fn [_ _ _] (reset! reconciled? true))]
+ (mt/with-dynamic-fn-redefs [remote-sync.task/last-version (constantly "base-B")
+ spec/extract-entities-for-export (constantly [{:dummy true}])
+ source/compute-merge (fn [_ _ _ _]
+ {:merged []
+ :conflicts [{:key [["Card" "A"]]
+ :ours {:path "collections/a.yaml" :content "x"}
+ :theirs {:path "collections/a.yaml" :content "y"}}]
+ :summary {:added 0 :updated 0 :removed 0}})
+ impl/load-snapshot! (fn [_ _ _] (reset! reconciled? true))]
(let [result (impl/export! (export-test-snapshot "remote-R") task-id "msg"
:merge? true
:source (export-test-source)
@@ -1932,13 +1932,13 @@ serdes/meta:
(default-branch [_] "main")
(snapshot [_] (export-test-snapshot "remote-R"))
(snapshot-at [_ _] nil))]
- (with-redefs [remote-sync.task/last-version (constantly "base-B")
- spec/extract-entities-for-export (constantly [{:dummy true}])
- source/compute-merge (fn [_ _ _ _]
- {:merged [{:path "collections/x.yaml" :content "x"}]
- :conflicts []
- :summary {:added 1 :updated 0 :removed 0}})
- impl/load-snapshot! (fn [_ _ _ & _] (reset! reconciled? true))]
+ (mt/with-dynamic-fn-redefs [remote-sync.task/last-version (constantly "base-B")
+ spec/extract-entities-for-export (constantly [{:dummy true}])
+ source/compute-merge (fn [_ _ _ _]
+ {:merged [{:path "collections/x.yaml" :content "x"}]
+ :conflicts []
+ :summary {:added 1 :updated 0 :removed 0}})
+ impl/load-snapshot! (fn [_ _ _ & _] (reset! reconciled? true))]
(let [result (impl/export! (export-test-snapshot "remote-R") task-id "msg"
:merge? true
:source no-resolve-source
@@ -1951,8 +1951,8 @@ serdes/meta:
(deftest export!-conflict-when-merge-base-unreachable-test
(testing "when merge is requested but the merge base is gone (force-push/rebase), export! returns :conflict"
(mt/with-temp [:model/RemoteSyncTask {task-id :id} {:sync_task_type "export"}]
- (with-redefs [remote-sync.task/last-version (constantly "base-B")
- spec/extract-entities-for-export (constantly [{:dummy true}])]
+ (mt/with-dynamic-fn-redefs [remote-sync.task/last-version (constantly "base-B")
+ spec/extract-entities-for-export (constantly [{:dummy true}])]
(let [result (impl/export! (export-test-snapshot "remote-R") task-id "msg"
:merge? true
:source (export-test-source)
@@ -1964,9 +1964,9 @@ serdes/meta:
(testing "when the remote advanced and neither force? nor merge? is set, export! refuses without writing or merging"
(mt/with-temp [:model/RemoteSyncTask {task-id :id} {:sync_task_type "export"}]
(let [merged? (atom false)]
- (with-redefs [remote-sync.task/last-version (constantly "base-B")
- spec/extract-entities-for-export (constantly [{:dummy true}])
- source/compute-merge (fn [& _] (reset! merged? true) {:merged [] :conflicts [] :summary {}})]
+ (mt/with-dynamic-fn-redefs [remote-sync.task/last-version (constantly "base-B")
+ spec/extract-entities-for-export (constantly [{:dummy true}])
+ source/compute-merge (fn [& _] (reset! merged? true) {:merged [] :conflicts [] :summary {}})]
(let [result (impl/export! (export-test-snapshot "remote-R") task-id "msg"
:source (export-test-source)
:base-snapshot (export-test-snapshot "base-B"))]
@@ -1979,9 +1979,9 @@ serdes/meta:
(testing "force? overwrites the remote wholesale (full export) even when it advanced — no merge"
(mt/with-temp [:model/RemoteSyncTask {task-id :id} {:sync_task_type "export"}]
(let [merged? (atom false)]
- (with-redefs [remote-sync.task/last-version (constantly "base-B")
- spec/exportable-entities (constantly {"Card" [999999999]}) ; absent id -> empty extraction; routing is what's under test
- source/compute-merge (fn [& _] (reset! merged? true) {:merged [] :conflicts [] :summary {}})]
+ (mt/with-dynamic-fn-redefs [remote-sync.task/last-version (constantly "base-B")
+ spec/exportable-entities (constantly {"Card" [999999999]}) ; absent id -> empty extraction; routing is what's under test
+ source/compute-merge (fn [& _] (reset! merged? true) {:merged [] :conflicts [] :summary {}})]
(let [result (impl/export! (export-test-snapshot "remote-R") task-id "msg"
:force? true
:source (export-test-source)
@@ -1998,9 +1998,9 @@ serdes/meta:
;; remote-sync.task/last-version equals the snapshot version, so not diverged. No dirty RemoteSyncObject
;; rows and the snapshot lists no files, so the normal export path is a no-op success — and crucially
;; never reaches the merge path.
- (with-redefs [remote-sync.task/last-version (constantly "remote-R")
- spec/extract-entities-for-export (constantly [{:dummy true}])
- source/compute-merge (fn [& _] (reset! merged? true) {:merged [] :conflicts [] :summary {}})]
+ (mt/with-dynamic-fn-redefs [remote-sync.task/last-version (constantly "remote-R")
+ spec/extract-entities-for-export (constantly [{:dummy true}])
+ source/compute-merge (fn [& _] (reset! merged? true) {:merged [] :conflicts [] :summary {}})]
(let [result (impl/export! (export-test-snapshot "remote-R") task-id "msg"
:source (export-test-source)
:base-snapshot (export-test-snapshot "remote-R"))]
@@ -2011,31 +2011,31 @@ serdes/meta:
(deftest preview-export-merge-not-diverged-test
(testing "preview reports no changes when the remote has not advanced"
- (with-redefs [remote-sync.task/last-version (constantly "remote-R") ; == snapshot version
- source/source-from-settings (constantly (export-test-source))]
+ (mt/with-dynamic-fn-redefs [remote-sync.task/last-version (constantly "remote-R") ; == snapshot version
+ source/source-from-settings (constantly (export-test-source))]
(is (= {:diverged? false :clean? true :conflicts [] :summary {:added 0 :updated 0 :removed 0}
:force-push-casualties {:deleted [] :overwritten []}}
(impl/preview-export-merge "main"))))))
(deftest preview-export-merge-clean-test
(testing "preview reports a clean merge with a summary when changes don't conflict"
- (with-redefs [remote-sync.task/last-version (constantly "base-B")
- source/source-from-settings (constantly (export-test-source))
- spec/extract-entities-for-export (constantly [{:dummy true}])
- source/preview-merge (fn [_ _ _ _]
- {:clean? true :conflicts []
- :summary {:added 1 :updated 0 :removed 0}})]
+ (mt/with-dynamic-fn-redefs [remote-sync.task/last-version (constantly "base-B")
+ source/source-from-settings (constantly (export-test-source))
+ spec/extract-entities-for-export (constantly [{:dummy true}])
+ source/preview-merge (fn [_ _ _ _]
+ {:clean? true :conflicts []
+ :summary {:added 1 :updated 0 :removed 0}})]
(is (= {:diverged? true :clean? true :conflicts [] :summary {:added 1 :updated 0 :removed 0}}
(impl/preview-export-merge "main"))))))
(deftest preview-export-merge-conflict-test
(testing "preview reports conflicts when the same entity changed on both sides"
- (with-redefs [remote-sync.task/last-version (constantly "base-B")
- source/source-from-settings (constantly (export-test-source))
- spec/extract-entities-for-export (constantly [{:dummy true}])
- source/preview-merge (fn [_ _ _ _]
- {:clean? false :conflicts ["Card A (collections/a.yaml)"]
- :summary {:added 0 :updated 0 :removed 0}})]
+ (mt/with-dynamic-fn-redefs [remote-sync.task/last-version (constantly "base-B")
+ source/source-from-settings (constantly (export-test-source))
+ spec/extract-entities-for-export (constantly [{:dummy true}])
+ source/preview-merge (fn [_ _ _ _]
+ {:clean? false :conflicts ["Card A (collections/a.yaml)"]
+ :summary {:added 0 :updated 0 :removed 0}})]
(is (= {:diverged? true :clean? false
:conflicts ["Card A (collections/a.yaml)"]
:summary {:added 0 :updated 0 :removed 0}}
@@ -2049,10 +2049,10 @@ serdes/meta:
(default-branch [_] "main")
(snapshot [_] (export-test-snapshot "remote-R"))
(snapshot-at [_ _] nil))]
- (with-redefs [remote-sync.task/last-version (constantly "gone-base")
- source/source-from-settings (constantly no-base-source)
- spec/extract-entities-for-export (constantly [{:dummy true}])
- source/force-push-casualties-no-base (fn [_ _] {:deleted ["Audit Logs"] :overwritten []})]
+ (mt/with-dynamic-fn-redefs [remote-sync.task/last-version (constantly "gone-base")
+ source/source-from-settings (constantly no-base-source)
+ spec/extract-entities-for-export (constantly [{:dummy true}])
+ source/force-push-casualties-no-base (fn [_ _] {:deleted ["Audit Logs"] :overwritten []})]
(let [result (impl/preview-export-merge "main")]
(is (true? (:diverged? result)))
(is (false? (:clean? result)))
@@ -2071,17 +2071,17 @@ serdes/meta:
:model_name "Local Card" :status_changed_at :%now}
:model/RemoteSyncObject _ {:model_type "Card" :model_id 9992 :status "synced"
:model_name "Remote Card" :status_changed_at :%now}]
- (with-redefs [source/compute-merge (fn [_ _ _ _]
- {:merged [{:path "collections/x.yaml" :content "y"}]
- :conflicts []
- :summary {:added 1 :updated 0 :removed 0}})
- ;; simulate the load marking everything synced (what the import insert does), then running
- ;; the in-transaction finalize (restore-dirty + set-version)
- impl/load-snapshot! (fn [_ _ _ & {:keys [finalize!]}]
- (t2/update! :model/RemoteSyncObject
- :model_id [:in [9991 9992]]
- {:status "synced"})
- (when finalize! (finalize!)))]
+ (mt/with-dynamic-fn-redefs [source/compute-merge (fn [_ _ _ _]
+ {:merged [{:path "collections/x.yaml" :content "y"}]
+ :conflicts []
+ :summary {:added 1 :updated 0 :removed 0}})
+ ;; simulate the load marking everything synced (what the import insert does), then running
+ ;; the in-transaction finalize (restore-dirty + set-version)
+ impl/load-snapshot! (fn [_ _ _ & {:keys [finalize!]}]
+ (t2/update! :model/RemoteSyncObject
+ :model_id [:in [9991 9992]]
+ {:status "synced"})
+ (when finalize! (finalize!)))]
(let [result (impl/import! (export-test-snapshot "remote-R") task-id
:merge? true
:base-snapshot (export-test-snapshot "base-B"))]
@@ -2099,13 +2099,13 @@ serdes/meta:
(mt/with-temp [:model/RemoteSyncTask {task-id :id} {:sync_task_type "import"}
:model/RemoteSyncObject _ {:model_type "Card" :model_id 8881 :status "delete"
:model_name "Deleted Card" :status_changed_at :%now}]
- (with-redefs [source/compute-merge (fn [_ _ _ _]
- {:merged [] :conflicts [] :summary {:added 0 :updated 0 :removed 0}})
- ;; simulate the load wiping and not re-inserting the deleted entity's row, then the
- ;; in-transaction finalize (restore-dirty + set-version)
- impl/load-snapshot! (fn [_ _ _ & {:keys [finalize!]}]
- (t2/delete! :model/RemoteSyncObject :model_id 8881)
- (when finalize! (finalize!)))]
+ (mt/with-dynamic-fn-redefs [source/compute-merge (fn [_ _ _ _]
+ {:merged [] :conflicts [] :summary {:added 0 :updated 0 :removed 0}})
+ ;; simulate the load wiping and not re-inserting the deleted entity's row, then the
+ ;; in-transaction finalize (restore-dirty + set-version)
+ impl/load-snapshot! (fn [_ _ _ & {:keys [finalize!]}]
+ (t2/delete! :model/RemoteSyncObject :model_id 8881)
+ (when finalize! (finalize!)))]
(let [result (impl/import! (export-test-snapshot "remote-R") task-id
:merge? true
:base-snapshot (export-test-snapshot "base-B"))]
@@ -2121,16 +2121,16 @@ serdes/meta:
:model_name "Locally Deleted" :status_changed_at :%now}
:model/RemoteSyncObject _ {:model_type "Card" :model_id 9992 :status "synced"
:model_name "Remote Card" :status_changed_at :%now}]
- (with-redefs [source/compute-merge (fn [_ _ _ _]
- {:merged [{:path "collections/remote.yaml" :content "y"}]
- :conflicts []
- :summary {:added 0 :updated 1 :removed 0}})
- ;; simulate the load: the remote change is applied (9992 stays synced), the deleted
- ;; entity's row is wiped (the load doesn't re-create it), then the finalize runs.
- impl/load-snapshot! (fn [_ _ _ & {:keys [finalize!]}]
- (t2/delete! :model/RemoteSyncObject :model_id 8881)
- (t2/update! :model/RemoteSyncObject :model_id 9992 {:status "synced"})
- (when finalize! (finalize!)))]
+ (mt/with-dynamic-fn-redefs [source/compute-merge (fn [_ _ _ _]
+ {:merged [{:path "collections/remote.yaml" :content "y"}]
+ :conflicts []
+ :summary {:added 0 :updated 1 :removed 0}})
+ ;; simulate the load: the remote change is applied (9992 stays synced), the deleted
+ ;; entity's row is wiped (the load doesn't re-create it), then the finalize runs.
+ impl/load-snapshot! (fn [_ _ _ & {:keys [finalize!]}]
+ (t2/delete! :model/RemoteSyncObject :model_id 8881)
+ (t2/update! :model/RemoteSyncObject :model_id 9992 {:status "synced"})
+ (when finalize! (finalize!)))]
(let [result (impl/import! (export-test-snapshot "remote-R") task-id
:merge? true
:base-snapshot (export-test-snapshot "base-B"))]
@@ -2146,13 +2146,13 @@ serdes/meta:
(deftest import!-merge-conflict-test
(testing "a local-only merge with a genuine conflict returns :conflict and does not load"
(mt/with-temp [:model/RemoteSyncTask {task-id :id} {:sync_task_type "import"}]
- (with-redefs [source/compute-merge (fn [_ _ _ _]
- {:merged []
- :conflicts [{:key [["Card" "A"]]
- :ours {:path "collections/a.yaml" :content "x"}
- :theirs {:path "collections/a.yaml" :content "z"}}]
- :summary {:added 0 :updated 0 :removed 0}})
- impl/load-snapshot! (fn [_ _ _] (throw (ex-info "should not load on conflict" {})))]
+ (mt/with-dynamic-fn-redefs [source/compute-merge (fn [_ _ _ _]
+ {:merged []
+ :conflicts [{:key [["Card" "A"]]
+ :ours {:path "collections/a.yaml" :content "x"}
+ :theirs {:path "collections/a.yaml" :content "z"}}]
+ :summary {:added 0 :updated 0 :removed 0}})
+ impl/load-snapshot! (fn [_ _ _] (throw (ex-info "should not load on conflict" {})))]
(let [result (impl/import! (export-test-snapshot "remote-R") task-id
:merge? true
:base-snapshot (export-test-snapshot "base-B"))]
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/incremental_import_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/incremental_import_test.clj
index edab7ea9fcb..42ccd5985ac 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/incremental_import_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/incremental_import_test.clj
@@ -92,12 +92,12 @@
path it took. Returns [result path], where path is :incremental (the fast-path ran) or :fallback (it
declined and import! ran the full load-snapshot!)."
[src]
- (let [real @#'impl/incremental-load-snapshot!
+ (let [real (mt/original-fn #'impl/incremental-load-snapshot!)
path (atom :fallback)]
- (with-redefs [impl/incremental-load-snapshot!
- (fn [& args] (let [r (apply real args)]
- (reset! path (if (= r :remote-sync/incremental-not-possible) :fallback :incremental))
- r))]
+ (mt/with-dynamic-fn-redefs [impl/incremental-load-snapshot!
+ (fn [& args] (let [r (apply real args)]
+ (reset! path (if (= r :remote-sync/incremental-not-possible) :fallback :incremental))
+ r))]
[(import-at! src "v1" :force? false) @path])))
(defn- run-differential!
@@ -200,8 +200,8 @@
src (rs.test/versioned-source :trees {"v0" f0 "v1" f1} :current "v0")
indexed (atom #{})]
(import-at! src "v0" :force? true) ; baseline (full) — local == v0
- (with-redefs [search/update! (fn [inst] (swap! indexed conj (:entity_id inst)))
- search/delete! (fn [& _] nil)]
+ (mt/with-dynamic-fn-redefs [search/update! (fn [inst] (swap! indexed conj (:entity_id inst)))
+ search/delete! (fn [& _] nil)]
(import-at! src "v1")) ; incremental edit of card_b only
(is (contains? @indexed b-eid) "the edited card is re-indexed")
(is (not (contains? @indexed a-eid)) "the unchanged card is NOT re-indexed")))))))
@@ -222,7 +222,7 @@
deleted (atom [])]
(import-at! src "v0" :force? true) ; baseline (full) — local == v0
(let [b-id (t2/select-one-pk :model/Card :entity_id b-eid)]
- (with-redefs [search/delete! (fn [model ids] (swap! deleted conj [model (vec ids)]))]
+ (mt/with-dynamic-fn-redefs [search/delete! (fn [model ids] (swap! deleted conj [model (vec ids)]))]
(import-at! src "v1")) ; incremental delete of card_b
(is (some (fn [[model ids]] (and (= :model/Card model) (some #{b-id} ids))) @deleted)
"the removed card is deleted from the search index by id"))))))))
@@ -270,9 +270,9 @@
(do-with-bench!
(fn [f0]
(let [src (rs.test/versioned-source :trees {"v0" f0} :current "v0")
- real @#'impl/incremental-load-snapshot!
+ real (mt/original-fn #'impl/incremental-load-snapshot!)
called? (atom false)]
- (with-redefs [impl/incremental-load-snapshot! (fn [& args] (reset! called? true) (apply real args))]
+ (mt/with-dynamic-fn-redefs [impl/incremental-load-snapshot! (fn [& args] (reset! called? true) (apply real args))]
;; no baseline import has run, so this is the first import: first-import? is true
(is (= :success (:status (import-at! src "v0" :force? false))))
(is (not @called?)
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/init_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/init_test.clj
index 11db8579782..c87e15a500e 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/init_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/init_test.clj
@@ -25,7 +25,7 @@
(testing "When remote sync is disabled and no remote-synced collection exists, nothing happens"
(mt/with-temporary-setting-values [:remote-sync-url nil]
(let [[calls capture] (capture-async-import!)]
- (with-redefs [impl/async-import! capture]
+ (mt/with-dynamic-fn-redefs [impl/async-import! capture]
(#'init/remote-sync-init)
(is (empty? @calls)))))))
@@ -34,7 +34,7 @@
(mt/with-temporary-setting-values [:remote-sync-url "file://my/repo.git"
:remote-sync-type :read-only
:remote-sync-branch nil]
- (with-redefs [remote-sync.object/dirty? (constantly false)]
+ (mt/with-dynamic-fn-redefs [remote-sync.object/dirty? (constantly false)]
(is (thrown-with-msg? clojure.lang.ExceptionInfo
#"no branch is set"
(#'init/remote-sync-init)))))))
@@ -45,7 +45,7 @@
:remote-sync-type :read-only
:remote-sync-branch "main"
:remote-sync-allow nil]
- (with-redefs [remote-sync.object/dirty? (constantly true)]
+ (mt/with-dynamic-fn-redefs [remote-sync.object/dirty? (constantly true)]
(is (thrown-with-msg? clojure.lang.ExceptionInfo
#"unpublished changes"
(#'init/remote-sync-init)))))))
@@ -57,8 +57,8 @@
:remote-sync-branch "main"
:remote-sync-allow "overwrite-unpublished"]
(let [[calls capture] (capture-async-import!)]
- (with-redefs [remote-sync.object/dirty? (constantly true)
- impl/async-import! capture]
+ (mt/with-dynamic-fn-redefs [remote-sync.object/dirty? (constantly true)
+ impl/async-import! capture]
(mt/with-temp [:model/Collection _ {:name "Synced" :is_remote_synced true}]
(#'init/remote-sync-init)
(is (= [["main" true {}]] @calls))))))))
@@ -70,8 +70,8 @@
:remote-sync-branch "develop"
:remote-sync-allow nil]
(let [[calls capture] (capture-async-import!)]
- (with-redefs [remote-sync.object/dirty? (constantly false)
- impl/async-import! capture]
+ (mt/with-dynamic-fn-redefs [remote-sync.object/dirty? (constantly false)
+ impl/async-import! capture]
;; Make sure no remote-synced collection exists for the test
(collection/clear-remote-synced-collection!)
(#'init/remote-sync-init)
@@ -83,8 +83,8 @@
:remote-sync-type :read-write
:remote-sync-branch nil]
(let [[calls capture] (capture-async-import!)]
- (with-redefs [remote-sync.object/dirty? (constantly false)
- impl/async-import! capture]
+ (mt/with-dynamic-fn-redefs [remote-sync.object/dirty? (constantly false)
+ impl/async-import! capture]
(collection/clear-remote-synced-collection!)
(#'init/remote-sync-init)
(is (empty? @calls)))))))
@@ -95,8 +95,8 @@
:remote-sync-type :read-write
:remote-sync-branch "main"]
(let [[calls capture] (capture-async-import!)]
- (with-redefs [remote-sync.object/dirty? (constantly false)
- impl/async-import! capture]
+ (mt/with-dynamic-fn-redefs [remote-sync.object/dirty? (constantly false)
+ impl/async-import! capture]
(mt/with-temp [:model/Collection _ {:name "Synced" :is_remote_synced true}]
(#'init/remote-sync-init)
(is (empty? @calls))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/settings_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/settings_test.clj
index 91cf7b96119..b4604636236 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/settings_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/settings_test.clj
@@ -152,7 +152,7 @@
(deftest check-and-update-remote-settings-env-var-aware-test
(testing "Settings sourced from env vars are not overwritten by check-and-update-remote-settings!"
- (with-redefs [settings/check-git-settings! (constantly true)]
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (constantly true)]
(mt/with-temp-env-var-value! [mb-remote-sync-url "file://env/url.git"
mb-remote-sync-token "env-token"
mb-remote-sync-branch "env-branch"]
@@ -171,7 +171,7 @@
(is (= "env-token" (settings/remote-sync-token)))
(is (= "env-branch" (settings/remote-sync-branch)))))))
(testing "Non-env-sourced settings are still updated normally"
- (with-redefs [settings/check-git-settings! (constantly true)]
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (constantly true)]
(mt/with-temporary-setting-values [:remote-sync-url nil
:remote-sync-token nil
:remote-sync-branch nil
@@ -205,8 +205,8 @@
(testing "check-and-update-remote-settings! must refuse when guards/task-running? returns true,
without changing any settings or calling git"
(let [check-git-call-count (atom 0)]
- (with-redefs [guards/task-running? (constantly true)
- settings/check-git-settings! (fn [_] (swap! check-git-call-count inc) true)]
+ (mt/with-dynamic-fn-redefs [guards/task-running? (constantly true)
+ settings/check-git-settings! (fn [_] (swap! check-git-call-count inc) true)]
(mt/with-temporary-setting-values [:remote-sync-url "file://my/repo.git"
:remote-sync-token nil
:remote-sync-type :read-only
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/explorations_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/explorations_test.clj
index 0f5ba356992..f98b50f0aca 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/explorations_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/explorations_test.clj
@@ -367,7 +367,7 @@
(testing "when the enforcement guard says the user IS sandboxed but the attribute lookup returns nil,
the token must NOT collapse to nil (the compatibility gate reads nil as 'unrestricted')"
(met/with-gtaps-for-user! :rasta (price-sandbox)
- (with-redefs [sandbox.field-values/field->sandbox-attributes-for-current-user (constantly nil)]
+ (mt/with-dynamic-fn-redefs [sandbox.field-values/field->sandbox-attributes-for-current-user (constantly nil)]
(let [token (perms/data-access-token {:database-id (mt/id) :table-ids #{(mt/id :venues)}})]
(testing "the sandbox dimension is present and scoped to the user (fail closed)"
(is (= (venues-token-for-lens
diff --git a/enterprise/backend/test/metabase_enterprise/security_center/api_test.clj b/enterprise/backend/test/metabase_enterprise/security_center/api_test.clj
index d3fab1c2878..8b4620bfa5b 100644
--- a/enterprise/backend/test/metabase_enterprise/security_center/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/security_center/api_test.clj
@@ -219,7 +219,7 @@
(mt/with-premium-features #{:admin-security-center}
(testing "body values are passed through to send-test-notification!"
(let [captured (atom nil)]
- (with-redefs [notification/send-test-notification! #(reset! captured %)]
+ (mt/with-dynamic-fn-redefs [notification/send-test-notification! #(reset! captured %)]
(mt/user-http-request :crowberto :post 200 "ee/security-center/test-notification"
{:email_recipients [{:type "notification-recipient/raw-value"
:details {:value "[email protected]"}}
@@ -234,15 +234,15 @@
(is (= "#form-channel" (:slack-channel @captured))))))
(testing "body distinguishes explicit nil slack_channel (disable) from missing key (fall back to setting)"
(let [captured (atom nil)]
- (with-redefs [notification/send-test-notification! #(reset! captured %)
- settings/security-center-slack-channel (constantly "#saved-channel")]
+ (mt/with-dynamic-fn-redefs [notification/send-test-notification! #(reset! captured %)
+ settings/security-center-slack-channel (constantly "#saved-channel")]
(mt/user-http-request :crowberto :post 200 "ee/security-center/test-notification"
{:email_recipients [{:type "notification-recipient/group"
:permissions_group_id 2}]
:slack_channel nil})
(is (nil? (:slack-channel @captured)) "explicit nil disables Slack for the test"))
- (with-redefs [notification/send-test-notification! #(reset! captured %)
- settings/security-center-slack-channel (constantly "#saved-channel")]
+ (mt/with-dynamic-fn-redefs [notification/send-test-notification! #(reset! captured %)
+ settings/security-center-slack-channel (constantly "#saved-channel")]
(mt/user-http-request :crowberto :post 200 "ee/security-center/test-notification"
{:email_recipients [{:type "notification-recipient/group"
:permissions_group_id 2}]})
@@ -250,8 +250,8 @@
(testing "missing email_recipients falls back to saved setting"
(let [captured (atom nil)
saved-emails [{:type :notification-recipient/raw-value :details {:value "[email protected]"}}]]
- (with-redefs [notification/send-test-notification! #(reset! captured %)
- settings/security-center-email-recipients (constantly saved-emails)
- settings/security-center-slack-channel (constantly nil)]
+ (mt/with-dynamic-fn-redefs [notification/send-test-notification! #(reset! captured %)
+ settings/security-center-email-recipients (constantly saved-emails)
+ settings/security-center-slack-channel (constantly nil)]
(mt/user-http-request :crowberto :post 200 "ee/security-center/test-notification" {})
(is (= saved-emails (:email-recipients @captured)))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/security_center/notification_test.clj b/enterprise/backend/test/metabase_enterprise/security_center/notification_test.clj
index dfa2a5b2fa0..49e3c618037 100644
--- a/enterprise/backend/test/metabase_enterprise/security_center/notification_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/security_center/notification_test.clj
@@ -389,8 +389,8 @@
form-slack-channel "#form-channel"]
(mt/with-temporary-setting-values [admin-email nil
slack-token-valid? true]
- (with-redefs [settings/security-center-email-recipients (constantly saved-emails)
- settings/security-center-slack-channel (constantly "#saved-channel")]
+ (mt/with-dynamic-fn-redefs [settings/security-center-email-recipients (constantly saved-emails)
+ settings/security-center-slack-channel (constantly "#saved-channel")]
(with-send-redef (fn [notif & _] (reset! sent notif))
(notification/send-test-notification! {:email-recipients form-emails
:slack-channel form-slack-channel})
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/db/datasource_mode_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/db/datasource_mode_test.clj
index ee8b464b78a..c966d25e37e 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/db/datasource_mode_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/db/datasource_mode_test.clj
@@ -130,35 +130,40 @@
mdb/db-type (constantly :postgres)]
(testing "nothing cached (and mode :unavailable) before the app db is set up"
(with-support-cache nil
- (with-redefs [mdb/db-is-set-up? (constantly false)
- semantic.db.datasource/check-app-db-pgvector-support
- (fn [] (throw (AssertionError. "must not probe before the app db is set up")))]
+ (mt/with-dynamic-fn-redefs
+ [mdb/db-is-set-up? (constantly false)
+ semantic.db.datasource/check-app-db-pgvector-support
+ (fn [] (throw (AssertionError. "must not probe before the app db is set up")))]
(is (= :unavailable (semantic.db.datasource/pgvector-mode)))
(is (nil? @semantic.db.datasource/app-db-pgvector-support)))))
(testing "check runs exactly once; its result is cached for subsequent calls"
(with-support-cache nil
(let [calls (atom 0)]
- (with-redefs [mdb/db-is-set-up? (constantly true)
- semantic.db.datasource/check-app-db-pgvector-support (fn [] (swap! calls inc) true)]
+ (mt/with-dynamic-fn-redefs
+ [mdb/db-is-set-up? (constantly true)
+ semantic.db.datasource/check-app-db-pgvector-support (fn [] (swap! calls inc) true)]
(is (= :app-db (semantic.db.datasource/pgvector-mode)))
(is (= :app-db (semantic.db.datasource/pgvector-mode)))
(is (= 1 @calls))
(is (true? @semantic.db.datasource/app-db-pgvector-support))))))
(testing "a failed probe reads as unavailable, does NOT latch, and backs off before retrying"
(with-support-cache nil
- (with-redefs [mdb/db-is-set-up? (constantly true)
- semantic.db.datasource/check-app-db-pgvector-support (fn [] (throw (ex-info "boom" {})))]
+ (mt/with-dynamic-fn-redefs
+ [mdb/db-is-set-up? (constantly true)
+ semantic.db.datasource/check-app-db-pgvector-support (fn [] (throw (ex-info "boom" {})))]
(is (= :unavailable (semantic.db.datasource/pgvector-mode)))
(is (nil? @semantic.db.datasource/app-db-pgvector-support)))
(testing "within the backoff window the check must not run again"
- (with-redefs [mdb/db-is-set-up? (constantly true)
- semantic.db.datasource/check-app-db-pgvector-support
- (fn [] (throw (AssertionError. "must not re-probe during backoff")))]
+ (mt/with-dynamic-fn-redefs
+ [mdb/db-is-set-up? (constantly true)
+ semantic.db.datasource/check-app-db-pgvector-support
+ (fn [] (throw (AssertionError. "must not re-probe during backoff")))]
(is (= :unavailable (semantic.db.datasource/pgvector-mode)))))
(testing "once the window clears, the next call re-probes"
(reset! semantic.db.datasource/probe-cooldown-timer nil)
- (with-redefs [mdb/db-is-set-up? (constantly true)
- semantic.db.datasource/check-app-db-pgvector-support (constantly true)]
+ (mt/with-dynamic-fn-redefs
+ [mdb/db-is-set-up? (constantly true)
+ semantic.db.datasource/check-app-db-pgvector-support (constantly true)]
(is (= :app-db (semantic.db.datasource/pgvector-mode)))))))
;; This exercises the false->true transition with the probe mocked.
;; The real thing (an app-db role reads unsupported, an admin runs CREATE EXTENSION out-of-band, the
@@ -168,30 +173,35 @@
;; would be flaky against the database shared with other tests between runs.
(testing "an unsupported probe is NOT latched — it re-probes after the cooldown, so a runtime install is picked up"
(with-support-cache nil
- (with-redefs [mdb/db-is-set-up? (constantly true)
- semantic.db.datasource/check-app-db-pgvector-support (constantly false)]
+ (mt/with-dynamic-fn-redefs
+ [mdb/db-is-set-up? (constantly true)
+ semantic.db.datasource/check-app-db-pgvector-support (constantly false)]
(is (= :unavailable (semantic.db.datasource/pgvector-mode)))
(is (nil? @semantic.db.datasource/app-db-pgvector-support))
(testing "within the cooldown the check must not run again"
- (with-redefs [mdb/db-is-set-up? (constantly true)
- semantic.db.datasource/check-app-db-pgvector-support
- (fn [] (throw (AssertionError. "must not re-probe during cooldown")))]
+ (mt/with-dynamic-fn-redefs
+ [mdb/db-is-set-up? (constantly true)
+ semantic.db.datasource/check-app-db-pgvector-support
+ (fn [] (throw (AssertionError. "must not re-probe during cooldown")))]
(is (= :unavailable (semantic.db.datasource/pgvector-mode))))))
(testing "cooldown elapsed: pgvector installed at runtime is now picked up (no restart)"
(reset! semantic.db.datasource/probe-cooldown-timer nil)
- (with-redefs [mdb/db-is-set-up? (constantly true)
- semantic.db.datasource/check-app-db-pgvector-support (constantly true)]
+ (mt/with-dynamic-fn-redefs
+ [mdb/db-is-set-up? (constantly true)
+ semantic.db.datasource/check-app-db-pgvector-support (constantly true)]
(is (= :app-db (semantic.db.datasource/pgvector-mode)))))))
(testing "a confirmed true latches for the JVM lifetime; tests/REPL reset it"
(with-support-cache nil
- (with-redefs [mdb/db-is-set-up? (constantly true)
- semantic.db.datasource/check-app-db-pgvector-support (constantly true)]
+ (mt/with-dynamic-fn-redefs
+ [mdb/db-is-set-up? (constantly true)
+ semantic.db.datasource/check-app-db-pgvector-support (constantly true)]
(is (= :app-db (semantic.db.datasource/pgvector-mode)))
(is (true? @semantic.db.datasource/app-db-pgvector-support)))
(testing "latched: a now-failing check is never consulted"
- (with-redefs [mdb/db-is-set-up? (constantly true)
- semantic.db.datasource/check-app-db-pgvector-support
- (fn [] (throw (AssertionError. "must not re-probe after a confirmed true")))]
+ (mt/with-dynamic-fn-redefs
+ [mdb/db-is-set-up? (constantly true)
+ semantic.db.datasource/check-app-db-pgvector-support
+ (fn [] (throw (AssertionError. "must not re-probe after a confirmed true")))]
(is (= :app-db (semantic.db.datasource/pgvector-mode)))))))))
(deftest unlicensed-availability-check-does-not-probe-test
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/embedding_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/embedding_test.clj
index 6bd5e24ca68..b67752bdd8d 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/embedding_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/embedding_test.clj
@@ -139,15 +139,16 @@
analytics-calls (atom [])
tracking-calls (atom [])
resolution-calls (atom [])]
- (with-redefs [embeddings.provider/resolve-model (fn [requested]
- (swap! resolution-calls conj requested)
- (assoc requested :model-name "local-model"))
- embeddings.provider/embed-text (fn [_ text _] [text])
- embeddings.provider/embed-texts (fn [_ texts _] (mapv vector texts))
- analytics/inc! (fn [metric labels value]
- (swap! analytics-calls conj [metric labels value]))
- semantic.models.token-tracking/record-tokens (fn [& args]
- (swap! tracking-calls conj args))]
+ (mt/with-dynamic-fn-redefs
+ [embeddings.provider/resolve-model (fn [requested]
+ (swap! resolution-calls conj requested)
+ (assoc requested :model-name "local-model"))
+ embeddings.provider/embed-text (fn [_ text _] [text])
+ embeddings.provider/embed-texts (fn [_ texts _] (mapv vector texts))
+ analytics/inc! (fn [metric labels value]
+ (swap! analytics-calls conj [metric labels value]))
+ semantic.models.token-tracking/record-tokens (fn [& args]
+ (swap! tracking-calls conj args))]
(embedding/get-embedding model "Hello world" :type :query :record-tokens? true)
(embedding/get-embeddings-batch model ["Hello world" "again"] :type :index :record-tokens? true)
(testing "local calls report approximate token metrics and persistent usage"
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/health_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/health_test.clj
index e030cbb8ed4..c942528c131 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/health_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/health_test.clj
@@ -195,32 +195,32 @@
;; Tests the raw probe (`embedding-service-reachable?` is TTL-memoized, so calling it across cases would
;; return a stale cached result).
-;; ^:synchronized: redefs the process-global `get-configured-model` / `get-embedding` via with-redefs, so it
-;; must not run concurrently with other tests (e.g. entity-retrieval-available? reads get-configured-model).
+;; ^:synchronized: shares the process-global probe cache with other tests, so it must not run concurrently.
(deftest ^:synchronized probe-embedding-service-test
(testing "a successful embed reads as reachable; the probe bypasses the breaker and silences snowplow"
(let [seen (atom nil)]
- ;; get-embedding is a multimethod; with-dynamic-fn-redefs can't patch those, so with-redefs is required.
- (with-redefs [semantic.embedding/get-configured-model (constantly {:model-name "m"})
- semantic.embedding/get-embedding
- (fn [_model _text opts]
- (reset! seen (assoc opts :bypass semantic.embedding/*bypass-circuit-breaker*))
- [0.1 0.2])]
+ (mt/with-dynamic-fn-redefs
+ [semantic.embedding/get-configured-model (constantly {:model-name "m"})
+ semantic.embedding/get-embedding
+ (fn [_model _text opts]
+ (reset! seen (assoc opts :bypass semantic.embedding/*bypass-circuit-breaker*))
+ [0.1 0.2])]
(is (=? {:reachable? true :error nil} (#'embedding-health/probe-embedding-service)))
(is (=? {:bypass true :snowplow? false :record-tokens? false} @seen)
"the probe runs with the breaker bypassed, snowplow silenced, and tokens unrecorded"))))
(testing "an embedding failure reads as unreachable and captures the message"
- (with-redefs [semantic.embedding/get-configured-model (constantly {:model-name "m"})
- semantic.embedding/get-embedding (fn [& _] (throw (ex-info "connection refused" {})))]
+ (mt/with-dynamic-fn-redefs
+ [semantic.embedding/get-configured-model (constantly {:model-name "m"})
+ semantic.embedding/get-embedding (fn [& _] (throw (ex-info "connection refused" {})))]
(is (=? {:reachable? false :error "connection refused"}
(#'embedding-health/probe-embedding-service))))))
(deftest ^:synchronized breaker-transition-probe-cache-test
(testing "open and half-open transitions reuse the probe; recovery clears it"
(let [probes (atom 0)]
- ;; get-embedding is a multimethod; with-dynamic-fn-redefs can't patch those, so with-redefs is required.
- (with-redefs [semantic.embedding/get-configured-model (constantly {:model-name "m"})
- semantic.embedding/get-embedding (fn [& _] (swap! probes inc) [0.1])]
+ (mt/with-dynamic-fn-redefs
+ [semantic.embedding/get-configured-model (constantly {:model-name "m"})
+ semantic.embedding/get-embedding (fn [& _] (swap! probes inc) [0.1])]
(mt/with-dynamic-fn-redefs [health-inspector/run-and-save-check! (constantly nil)]
(memoize/memo-clear! @#'embedding-health/embedding-service-reachable?*)
(embedding-health/embedding-service-reachable?)
@@ -242,12 +242,13 @@
before @state]
(try
(reset! state {:running? false, :last-start-ns nil})
- (with-redefs [semantic.embedding/get-configured-model (constantly {:model-name "m"})
- semantic.embedding/get-embedding
- (fn [& _]
- (when (= 2 (swap! calls inc))
- (.countDown completed))
- [0.1])]
+ (mt/with-dynamic-fn-redefs
+ [semantic.embedding/get-configured-model (constantly {:model-name "m"})
+ semantic.embedding/get-embedding
+ (fn [& _]
+ (when (= 2 (swap! calls inc))
+ (.countDown completed))
+ [0.1])]
(mt/with-dynamic-fn-redefs
[semantic.embedding/embedder-circuit-untrusted? #(< @calls 2)
embedding-health/schedule-recovery! future-call]
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/indexer_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/indexer_test.clj
index 7dfad388827..26de8c5c189 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/indexer_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/indexer_test.clj
@@ -53,18 +53,24 @@
(let [metadata-row (get-metadata-row! pgvector index-metadata index)
initial-watermark (semantic.gate/resume-watermark metadata-row)
indexing-state (semantic.indexer/init-indexing-state metadata-row)
- {poll-proxy :proxy poll-calls :calls} (semantic.tu/spy semantic.gate/poll)
- {upsert-proxy :proxy upsert-calls :calls} (semantic.tu/spy semantic.index/upsert-index!)
- {delete-proxy :proxy delete-calls :calls} (semantic.tu/spy semantic.index/delete-from-index!)
+ ;; capture the unpatched fns: other tests here redefine these vars, and once a var is
+ ;; proxied a bare capture would make the spy call itself
+ {poll-proxy :proxy poll-calls :calls}
+ (semantic.tu/spy (mt/original-fn #'semantic.gate/poll))
+ {upsert-proxy :proxy upsert-calls :calls}
+ (semantic.tu/spy (mt/original-fn #'semantic.index/upsert-index!))
+ {delete-proxy :proxy delete-calls :calls}
+ (semantic.tu/spy (mt/original-fn #'semantic.index/delete-from-index!))
clear-spies (fn []
(reset! poll-calls [])
(reset! upsert-calls [])
(reset! delete-calls []))]
(is (= initial-watermark (:watermark @indexing-state)))
(testing "gate is empty, poll counts should be zero - and upsert/delete should not be called"
- (with-redefs [semantic.index/upsert-index! upsert-proxy
- semantic.index/delete-from-index! delete-proxy
- semantic.gate/poll poll-proxy]
+ (mt/with-dynamic-fn-redefs
+ [semantic.index/upsert-index! upsert-proxy
+ semantic.index/delete-from-index! delete-proxy
+ semantic.gate/poll poll-proxy]
(semantic.indexer/indexing-step pgvector index-metadata index indexing-state)
(is (= [] @upsert-calls))
(is (= [] @delete-calls))
@@ -80,9 +86,10 @@
(testing "add some data to the gate we should see upsert / delete be called"
(clear-spies)
(semantic.gate/gate-documents! pgvector index-metadata [(version c1 t1) (delete c2 t2)])
- (with-redefs [semantic.index/upsert-index! upsert-proxy
- semantic.index/delete-from-index! delete-proxy
- semantic.gate/poll poll-proxy]
+ (mt/with-dynamic-fn-redefs
+ [semantic.index/upsert-index! upsert-proxy
+ semantic.index/delete-from-index! delete-proxy
+ semantic.gate/poll poll-proxy]
(semantic.indexer/indexing-step pgvector index-metadata index indexing-state)
(is (= 1 (count @upsert-calls)))
(is (= 1 (count @delete-calls)))
@@ -97,9 +104,10 @@
(semantic.gate/resume-watermark (get-metadata-row! pgvector index-metadata index)))))))))
(testing "stepping again with no new data does nothing"
(clear-spies)
- (with-redefs [semantic.index/upsert-index! upsert-proxy
- semantic.index/delete-from-index! delete-proxy
- semantic.gate/poll poll-proxy]
+ (mt/with-dynamic-fn-redefs
+ [semantic.index/upsert-index! upsert-proxy
+ semantic.index/delete-from-index! delete-proxy
+ semantic.gate/poll poll-proxy]
(semantic.indexer/indexing-step pgvector index-metadata index indexing-state)
(is (= 0 (count @upsert-calls)))
(is (= 0 (count @delete-calls)))
@@ -109,9 +117,10 @@
(testing "add some more data, picked up"
(clear-spies)
(semantic.gate/gate-documents! pgvector index-metadata [(version c2 t3)])
- (with-redefs [semantic.index/upsert-index! upsert-proxy
- semantic.index/delete-from-index! delete-proxy
- semantic.gate/poll poll-proxy]
+ (mt/with-dynamic-fn-redefs
+ [semantic.index/upsert-index! upsert-proxy
+ semantic.index/delete-from-index! delete-proxy
+ semantic.gate/poll poll-proxy]
(semantic.indexer/indexing-step pgvector index-metadata index indexing-state)
(is (= 1 (count @upsert-calls)))
(is (= 0 (count @delete-calls)))
@@ -121,9 +130,10 @@
(clear-spies)
(semantic.gate/gate-documents! pgvector index-metadata [(version c3 t3)])
(let [previous-state @indexing-state]
- (with-redefs [semantic.index/upsert-index! (fn [& _] (throw (Exception. "Boom")))
- semantic.index/delete-from-index! delete-proxy
- semantic.gate/poll poll-proxy]
+ (mt/with-dynamic-fn-redefs
+ [semantic.index/upsert-index! (fn [& _] (throw (Exception. "Boom")))
+ semantic.index/delete-from-index! delete-proxy
+ semantic.gate/poll poll-proxy]
(is (thrown-with-msg? Exception #"Boom" (semantic.indexer/indexing-step pgvector index-metadata index indexing-state)))
(is (= 0 (count @delete-calls)))
(is (= 1 (count @poll-calls)))
@@ -131,9 +141,10 @@
(is (= previous-state @indexing-state)))))
(testing "exceptions are recovered from"
(clear-spies)
- (with-redefs [semantic.index/upsert-index! upsert-proxy
- semantic.index/delete-from-index! delete-proxy
- semantic.gate/poll poll-proxy]
+ (mt/with-dynamic-fn-redefs
+ [semantic.index/upsert-index! upsert-proxy
+ semantic.index/delete-from-index! delete-proxy
+ semantic.gate/poll poll-proxy]
(semantic.indexer/indexing-step pgvector index-metadata index indexing-state)
(is (= 1 (count @upsert-calls)))
(is (= 0 (count @delete-calls)))
diff --git a/enterprise/backend/test/metabase_enterprise/support_access_grants/session_integration_test.clj b/enterprise/backend/test/metabase_enterprise/support_access_grants/session_integration_test.clj
index 946d628cc69..ed56e6063d6 100644
--- a/enterprise/backend/test/metabase_enterprise/support_access_grants/session_integration_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/support_access_grants/session_integration_test.clj
@@ -330,9 +330,9 @@
(deftest forgot-password-support-user-no-active-grant-test
(testing "POST /api/session/forgot_password - Support user with no active grant gets no email"
- (with-redefs [api.session/forgot-password-impl
- (let [orig @#'api.session/forgot-password-impl]
- (fn [& args] (u/deref-with-timeout (apply orig args) 1000)))]
+ (mt/with-dynamic-fn-redefs [api.session/forgot-password-impl
+ (let [orig (mt/original-fn #'api.session/forgot-password-impl)]
+ (fn [& args] (u/deref-with-timeout (apply orig args) 1000)))]
(mt/with-temp [:model/User user {:first_name "support"
:last_name "user"
@@ -348,14 +348,14 @@
(deftest forgot-password-support-user-active-grant-test
(testing "POST /api/session/forgot_password - Support user with active grant gets a refreshed token"
- (with-redefs [api.session/forgot-password-impl
- (let [orig @#'api.session/forgot-password-impl]
- (fn [& args] (u/deref-with-timeout (apply orig args) 1000)))]
+ (mt/with-dynamic-fn-redefs [api.session/forgot-password-impl
+ (let [orig (mt/original-fn #'api.session/forgot-password-impl)]
+ (fn [& args] (u/deref-with-timeout (apply orig args) 1000)))]
(mt/with-temp [:model/User {creator-id :id} {}]
(mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity :model/User]
- (with-redefs [sag.settings/support-access-grant-email (constantly "[email protected]")
- sag.settings/support-access-grant-first-name (constantly "Support")
- sag.settings/support-access-grant-last-name (constantly "User")]
+ (mt/with-dynamic-fn-redefs [sag.settings/support-access-grant-email (constantly "[email protected]")
+ sag.settings/support-access-grant-first-name (constantly "Support")
+ sag.settings/support-access-grant-last-name (constantly "User")]
(let [grant (grants/create-grant! creator-id 60 "TICKET-FORGOT" "Test forgot password")
original-token (:token grant)]
(is (some? original-token) "Grant should create a token")
@@ -386,14 +386,14 @@
(deftest forgot-password-then-reset-preserves-support-provider-test
(testing "Consuming a refreshed support-access token via reset_password keeps the support-access-grant provider"
- (with-redefs [api.session/forgot-password-impl
- (let [orig @#'api.session/forgot-password-impl]
- (fn [& args] (u/deref-with-timeout (apply orig args) 1000)))]
+ (mt/with-dynamic-fn-redefs [api.session/forgot-password-impl
+ (let [orig (mt/original-fn #'api.session/forgot-password-impl)]
+ (fn [& args] (u/deref-with-timeout (apply orig args) 1000)))]
(mt/with-temp [:model/User {creator-id :id} {}]
(mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity :model/User]
- (with-redefs [sag.settings/support-access-grant-email (constantly "[email protected]")
- sag.settings/support-access-grant-first-name (constantly "Support")
- sag.settings/support-access-grant-last-name (constantly "User")]
+ (mt/with-dynamic-fn-redefs [sag.settings/support-access-grant-email (constantly "[email protected]")
+ sag.settings/support-access-grant-first-name (constantly "Support")
+ sag.settings/support-access-grant-last-name (constantly "User")]
(let [grant (grants/create-grant! creator-id 60 "TICKET-PROVIDER" "Test provider preservation")]
(is (some? (:token grant)) "Grant should create a token")
(mt/with-temporary-setting-values [site-url "http://test.example.com"]
diff --git a/mage/src/mage/kondo.clj b/mage/src/mage/kondo.clj
index af79e012bf0..a59bf531c1e 100644
--- a/mage/src/mage/kondo.clj
+++ b/mage/src/mage/kondo.clj
@@ -1,5 +1,6 @@
(ns mage.kondo
(:require
+ [clojure.java.io :as io]
[clojure.string :as str]
[mage.shell :as shell]
[mage.util :as u]))
@@ -48,10 +49,43 @@
(shell/sh "rm" "-rf" ".clj-kondo/metosin/malli-types-clj/")
(shell/sh "rm" "-rf" ".clj-kondo/.cache"))
+(def ^:private ^java.io.File warm-cache-marker
+ "Written when a warm pass over every root finishes. Lives inside the cache, so [[clear-cache!]] removes it too."
+ (io/file u/project-root-directory ".clj-kondo" ".cache" "warmed"))
+
+(defn warm-cache!
+ "Lint `roots` once, discarding the findings, to fill the cache Kondo keeps under `.clj-kondo/.cache`.
+ With no `roots`, lints everything [[kondo]] does plus `dev/src`, which defines vars that `dev/test` redefines.
+
+ Hooks that ask about another namespace's vars (`hooks/ns-analysis`) read that cache and nothing else,
+ and Kondo writes it only after every file in a run has been analysed. A single pass over a cold cache
+ therefore tells those hooks nothing, and they silently skip their checks."
+ ([]
+ (warm-cache! nil))
+ ([roots]
+ (println "Warming the Kondo cache so cache-reading hooks can see every namespace...")
+ ;; Only a pass over every root may mark the cache warm. Drop the marker first, so an interrupted pass can't leave
+ ;; an old one next to a partial cache.
+ (when-not (seq roots)
+ (io/delete-file warm-cache-marker true))
+ (let [command (if (seq roots)
+ (list* "-M:kondo" "--lint" roots)
+ ["-M:kondo:kondo/all" "dev/src"])
+ {:keys [exit err]} (apply shell/sh* {:quiet? true} "clojure" command)]
+ ;; Kondo exits 2 for warnings and 3 for errors. Any other nonzero exit means the pass did not finish, and a
+ ;; partial cache would silence the same hooks this exists to feed.
+ (when-not (#{0 2 3} exit)
+ (throw (ex-info (str "Warming the Kondo cache failed:\n" (str/join "\n" err))
+ {:exit-code 1})))
+ (when-not (seq roots)
+ (io/make-parents warm-cache-marker)
+ (spit warm-cache-marker "")))))
+
(defn- kondo*
[args]
(copy-configs-if-needed!)
(clear-cache!)
+ (warm-cache!)
(let [command (if (empty? args)
(do
(println "Hunker down, we're running kondo against everything we usually lint...")
@@ -81,6 +115,14 @@
(println "Files:")
(doseq [filename updated-files]
(println " " filename))
+ ;; Reuse a finished warm pass so this stays fast. A cache without the marker may be partial, from an editor or
+ ;; an interrupted run, and would leave cache-reading hooks silent.
+ ;;
+ ;; The marker says a pass finished, not that the cache still matches the sources. Analysis from an earlier
+ ;; revision is accepted here in exchange for speed: [[kondo]] clears the cache and warms it again on every run,
+ ;; and that is the entry point CI uses.
+ (when-not (.exists warm-cache-marker)
+ (warm-cache!))
(let [{:keys [exit], :or {exit -1}} (apply shell/sh* "clojure" "-M:kondo" "--lint" updated-files)]
(System/exit exit))))
diff --git a/mage/src/mage/kondo_ratchet.clj b/mage/src/mage/kondo_ratchet.clj
index 3778786ebde..50ec948dac0 100644
--- a/mage/src/mage/kondo_ratchet.clj
+++ b/mage/src/mage/kondo_ratchet.clj
@@ -5,6 +5,7 @@
[clojure.edn :as edn]
[clojure.string :as str]
[dev.kondo-ratchet :as kondo-ratchet]
+ [mage.kondo :as kondo]
[mage.shell :as shell]))
(set! *warn-on-reflection* true)
@@ -335,6 +336,8 @@
pre-removal baseline, so files with pre-existing findings are excluded from the sweep and reported.
An `--audit` removal that sticks takes its stale marker comment with it."
[parsed]
+ ;; Without this, hooks reading the analysis cache report nothing and their ignores all look redundant.
+ (kondo/warm-cache! lint-roots)
(println "Running kondo with :redundant-ignore enabled (full lint, takes a minute or two)...")
(let [audit? (get-in parsed [:options :audit])
findings (kondo-findings! :redundant-ignore lint-roots)
@@ -474,6 +477,8 @@
[[linter-arg & paths]]
(when (str/blank? (str linter-arg))
(throw (ex-info "Usage: ./bin/mage kondo-insert-ignores LINTER [PATHS...]" {:exit-code 1})))
+ ;; Without this, a cache-reading hook linter finds no sites at all.
+ (kondo/warm-cache! lint-roots)
(let [linter (keyword (str/replace-first linter-arg #"^:" ""))
roots (or (seq paths) lint-roots)
_ (println (format "Running kondo with %s enabled over %s..." linter (str/join " " roots)))
diff --git a/modules/drivers/athena/test/metabase/driver/athena_test.clj b/modules/drivers/athena/test/metabase/driver/athena_test.clj
index 0770e2edd2f..f33616232ef 100644
--- a/modules/drivers/athena/test/metabase/driver/athena_test.clj
+++ b/modules/drivers/athena/test/metabase/driver/athena_test.clj
@@ -292,7 +292,7 @@
(defn- query->native! [query]
(let [check-sql-fn (fn [_driver _conn sql _params _canceled-chan]
(throw (ex-info "DONE" {:sql sql})))]
- (with-redefs [sql-jdbc.execute/statement-or-prepared-statement check-sql-fn]
+ (mt/with-dynamic-fn-redefs [sql-jdbc.execute/statement-or-prepared-statement check-sql-fn]
(try
(qp/process-query query)
(catch Throwable e
@@ -302,7 +302,7 @@
;; TODO: If we are extending remove remark functionality to other drivers, we should consider making this
;; test (1) general, so other drivers can use it and (2) parallel. That would require making
;; `sql-jdbc.execute/statement-or-prepared-statement` dynamic so it can be temporarily modified using `binding`
-;; instead of `with-redefs` in [[query->native!]].
+;; instead of `mt/with-dynamic-fn-redefs` in [[query->native!]].
;; TODO: If that is the case, also the solution should be generalized, taking into account existing functionality
;; for removing remark in other drivers, eg. bigquery. Generalization could be accomplished with help
;; of [[metabase.driver.sql-jdbc.execute/inject-remark]].
@@ -404,10 +404,10 @@
(lib/filter (lib/= (meta/field-metadata :venues :name) "BBQ"))
(lib/limit 1))
executed-query (atom nil)]
- (with-redefs [sql-jdbc.execute/execute-reducible-query (let [orig sql-jdbc.execute/execute-reducible-query]
- (fn [driver query context respond]
- (reset! executed-query query)
- (orig driver query context respond)))]
+ (mt/with-dynamic-fn-redefs [sql-jdbc.execute/execute-reducible-query (let [orig (mt/original-fn #'sql-jdbc.execute/execute-reducible-query)]
+ (fn [driver query context respond]
+ (reset! executed-query query)
+ (orig driver query context respond)))]
(try
(qp/process-query query)
(catch Throwable _))
diff --git a/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj b/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj
index 1d4883f3656..fa60f3c22b7 100644
--- a/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj
+++ b/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj
@@ -262,9 +262,9 @@
(let [requested (atom [])
next-size (fn [budget max-rows rows]
(reset! requested [])
- (with-redefs [bigquery/list-sample-page (fn [_bq size _token]
- (swap! requested conj size)
- (mock-page nil []))]
+ (mt/with-dynamic-fn-redefs [bigquery/list-sample-page (fn [_bq size _token]
+ (swap! requested conj size)
+ (mock-page nil []))]
(binding [bigquery/*page-byte-budget* budget]
((#'bigquery/adaptive-sample-next-page :table max-rows) (mock-page "tok" rows))
(first @requested))))
@@ -301,6 +301,9 @@
sizes (atom [])
requests (atom 0)
orig-next-page-size @#'bigquery/next-page-size]
+ ;; `next-page-size` takes and returns primitive longs, so compiled callers invoke it through `IFn$LLLLL`.
+ ;; The dynamic-redefs proxy is a plain variadic fn, and would throw ClassCastException there.
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [bigquery/next-page-size (fn ^long [^long budget ^long bytes ^long rows ^long rem]
(let [n (long (orig-next-page-size budget bytes rows rem))]
(swap! sizes conj n)
@@ -333,13 +336,13 @@
(fn [_cols reducible] (into [] reducible))
nil)]
(testing "a later page that comes back nil is reported, not silently truncated (#47339)"
- (with-redefs [bigquery/query-results-page (fn [_job _opts] nil)]
+ (mt/with-dynamic-fn-redefs [bigquery/query-results-page (fn [_job _opts] nil)]
(is (thrown-with-msg? clojure.lang.ExceptionInfo
#"Cannot get next page from BigQuery"
(consume)))))
(testing "a later page that throws surfaces the original error"
- (with-redefs [bigquery/query-results-page (fn [_job _opts]
- (throw (ex-info "onoes BigQuery failed to fetch a later page" {})))]
+ (mt/with-dynamic-fn-redefs [bigquery/query-results-page (fn [_job _opts]
+ (throw (ex-info "onoes BigQuery failed to fetch a later page" {})))]
(is (thrown-with-msg? clojure.lang.ExceptionInfo
#"onoes BigQuery failed to fetch a later page"
(consume)))))))
@@ -1022,7 +1025,7 @@
^com.google.cloud.bigquery.JobInfo _job-info
^"[Lcom.google.cloud.bigquery.BigQuery$JobOption;" _opts]
(throw sync-error)))]
- (with-redefs [bigquery/database-details->client (constantly mock-client)]
+ (mt/with-dynamic-fn-redefs [bigquery/database-details->client (constantly mock-client)]
(let [ex (try
(#'bigquery/execute-bigquery (constantly nil) {} "SELECT 1" [] nil)
nil
diff --git a/modules/drivers/redshift/test/metabase/driver/redshift_test.clj b/modules/drivers/redshift/test/metabase/driver/redshift_test.clj
index 5718234fcb3..ee0c04e193e 100644
--- a/modules/drivers/redshift/test/metabase/driver/redshift_test.clj
+++ b/modules/drivers/redshift/test/metabase/driver/redshift_test.clj
@@ -827,12 +827,12 @@
;; The other half of the guard above: moving the privilege calls into the select list means an unreadable
;; relation now reaches Clojure, and this is the one place that drops it.
(mt/with-temp [:model/Database db {:engine :redshift, :details {}}]
- (with-redefs [sql-jdbc.execute/reducible-query
- (fn [_database _sql]
- (for [[nm selectable] [["readable" true]
- ["unreadable" false]
- ["missing" nil]
- ["stringly" "false"]]]
- {:name nm, :schema "s", :type "table", :description nil, :selectable selectable}))]
+ (mt/with-dynamic-fn-redefs [sql-jdbc.execute/reducible-query
+ (fn [_database _sql]
+ (for [[nm selectable] [["readable" true]
+ ["unreadable" false]
+ ["missing" nil]
+ ["stringly" "false"]]]
+ {:name nm, :schema "s", :type "table", :description nil, :selectable selectable}))]
(is (= [{:name "readable", :schema "s", :description nil}]
(into [] (#'redshift/describe-database-tables db))))))))
diff --git a/test/metabase/analytics/metaplow_test.clj b/test/metabase/analytics/metaplow_test.clj
index 57ffe019333..317bfab1e35 100644
--- a/test/metabase/analytics/metaplow_test.clj
+++ b/test/metabase/analytics/metaplow_test.clj
@@ -59,9 +59,9 @@
(testing "When metaplow-tracking-enabled is false the event is not enqueued and the call returns false"
(mt/with-temporary-setting-values [metaplow-url nil]
(let [collector (atom [])]
- (with-redefs [metaplow/enqueue! (fn [payload]
- (swap! collector conj payload)
- true)]
+ (mt/with-dynamic-fn-redefs [metaplow/enqueue! (fn [payload]
+ (swap! collector conj payload)
+ true)]
(is (false? (metaplow/track-event! :snowplow/dashboard {:event :dashboard-created})))
(is (empty? @collector)))))))
@@ -70,6 +70,9 @@
anon-tracking-enabled true]
(testing "track-event! enqueues onto the real channel and the pipeline worker invokes send-event-with-retries!"
(let [received (promise)]
+ ;; the pipeline's worker threads are spawned once from a defonce delay, so they never inherit a
+ ;; test's *local-redefs*; only a root swap reaches them
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [metaplow/send-event-with-retries! (fn [payload]
(deliver received payload)
:sent)]
@@ -85,6 +88,9 @@
(testing "Sending 200 events: all of them traverse the pipeline"
(let [received (atom [])
latch (CountDownLatch. 200)]
+ ;; the pipeline's worker threads are spawned once from a defonce delay, so they never inherit a
+ ;; test's *local-redefs*; only a root swap reaches them
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [metaplow/send-event-with-retries! (fn [payload]
(swap! received conj payload)
(.countDown latch)
diff --git a/test/metabase/analyze/query_results_test.clj b/test/metabase/analyze/query_results_test.clj
index a10ef4aab63..7e60858280b 100644
--- a/test/metabase/analyze/query_results_test.clj
+++ b/test/metabase/analyze/query_results_test.clj
@@ -131,8 +131,8 @@
(deftest error-resilience-test
(testing "Data should come back even if there is an error during fingerprinting"
- (is (= 36 (with-redefs [fingerprinters/earliest test.sync/crash-fn]
+ (is (= 36 (mt/with-dynamic-fn-redefs [fingerprinters/earliest test.sync/crash-fn]
(-> (timeseries-dataset) :rows count)))))
(testing "Data should come back even if there is an error when calculating insights"
- (is (= 36 (with-redefs [insights/change test.sync/crash-fn]
+ (is (= 36 (mt/with-dynamic-fn-redefs [insights/change test.sync/crash-fn]
(-> (timeseries-dataset) :rows count))))))
diff --git a/test/metabase/app_db/connection_pool_setup_test.clj b/test/metabase/app_db/connection_pool_setup_test.clj
index 83ad4f1aaa9..6a4ef45e3e2 100644
--- a/test/metabase/app_db/connection_pool_setup_test.clj
+++ b/test/metabase/app_db/connection_pool_setup_test.clj
@@ -101,26 +101,27 @@
"recent-window-duration has elapsed but still recent")))))
(defn- with-config-overrides
- "Returns a fn replacement for `config/config-int` (or `config/config-bool`) that returns
- `overrides`' value for matching keys and the original config fn's value otherwise."
- [orig-fn overrides]
- (fn [k]
- (if (contains? overrides k)
- (get overrides k)
- (orig-fn k))))
+ "Returns a fn replacement for the config fn var `config-var` (`#'config/config-int` or
+ `#'config/config-bool`) that returns `overrides`' value for matching keys and the original's otherwise."
+ [config-var overrides]
+ (let [orig-fn (mt/original-fn config-var)]
+ (fn [k]
+ (if (contains? overrides k)
+ (get overrides k)
+ (orig-fn k)))))
(deftest application-db-connection-pool-props-defaults-test
(testing "default values are preserved when no overrides are set"
- (with-redefs [config/config-int (with-config-overrides config/config-int
- {:mb-application-db-max-connection-pool-size nil
- :mb-application-db-unreturned-connection-timeout nil
- :mb-application-db-unreturned-connection-timeout-seconds nil
- :mb-application-db-max-connection-age-seconds nil
- :mb-application-db-idle-connection-test-period-seconds nil
- :mb-application-db-max-idle-time-excess-connections-seconds nil
- :mb-application-db-checkout-timeout-ms nil})
- config/config-bool (with-config-overrides config/config-bool
- {:mb-application-db-test-connection-on-checkout nil})]
+ (mt/with-dynamic-fn-redefs [config/config-int (with-config-overrides #'config/config-int
+ {:mb-application-db-max-connection-pool-size nil
+ :mb-application-db-unreturned-connection-timeout nil
+ :mb-application-db-unreturned-connection-timeout-seconds nil
+ :mb-application-db-max-connection-age-seconds nil
+ :mb-application-db-idle-connection-test-period-seconds nil
+ :mb-application-db-max-idle-time-excess-connections-seconds nil
+ :mb-application-db-checkout-timeout-ms nil})
+ config/config-bool (with-config-overrides #'config/config-bool
+ {:mb-application-db-test-connection-on-checkout nil})]
(let [props (#'mdb.connection-pool-setup/application-db-connection-pool-props)]
(is (= 60 (get props "idleConnectionTestPeriod")))
(is (= 600 (get props "maxIdleTimeExcessConnections")))
@@ -133,49 +134,49 @@
(deftest application-db-connection-pool-props-overrides-test
(testing "MB_APPLICATION_DB_MAX_CONNECTION_AGE_SECONDS overrides maxConnectionAge"
- (with-redefs [config/config-int (with-config-overrides config/config-int
- {:mb-application-db-max-connection-age-seconds 0})]
+ (mt/with-dynamic-fn-redefs [config/config-int (with-config-overrides #'config/config-int
+ {:mb-application-db-max-connection-age-seconds 0})]
(is (= 0 (get (#'mdb.connection-pool-setup/application-db-connection-pool-props)
"maxConnectionAge"))
"setting maxConnectionAge to 0 must be honored (use case: RDS IAM auth via the AWS JDBC wrapper)")))
(testing "MB_APPLICATION_DB_IDLE_CONNECTION_TEST_PERIOD_SECONDS overrides idleConnectionTestPeriod"
- (with-redefs [config/config-int (with-config-overrides config/config-int
- {:mb-application-db-idle-connection-test-period-seconds 30})]
+ (mt/with-dynamic-fn-redefs [config/config-int (with-config-overrides #'config/config-int
+ {:mb-application-db-idle-connection-test-period-seconds 30})]
(is (= 30 (get (#'mdb.connection-pool-setup/application-db-connection-pool-props)
"idleConnectionTestPeriod")))))
(testing "MB_APPLICATION_DB_MAX_IDLE_TIME_EXCESS_CONNECTIONS_SECONDS overrides maxIdleTimeExcessConnections"
- (with-redefs [config/config-int (with-config-overrides config/config-int
- {:mb-application-db-max-idle-time-excess-connections-seconds 120})]
+ (mt/with-dynamic-fn-redefs [config/config-int (with-config-overrides #'config/config-int
+ {:mb-application-db-max-idle-time-excess-connections-seconds 120})]
(is (= 120 (get (#'mdb.connection-pool-setup/application-db-connection-pool-props)
"maxIdleTimeExcessConnections")))))
(testing "MB_APPLICATION_DB_TEST_CONNECTION_ON_CHECKOUT overrides testConnectionOnCheckout"
- (with-redefs [config/config-bool (with-config-overrides config/config-bool
- {:mb-application-db-test-connection-on-checkout true})]
+ (mt/with-dynamic-fn-redefs [config/config-bool (with-config-overrides #'config/config-bool
+ {:mb-application-db-test-connection-on-checkout true})]
(is (true? (get (#'mdb.connection-pool-setup/application-db-connection-pool-props)
"testConnectionOnCheckout")))))
(testing "MB_APPLICATION_DB_CHECKOUT_TIMEOUT_MS overrides checkoutTimeout"
- (with-redefs [config/config-int (with-config-overrides config/config-int
- {:mb-application-db-checkout-timeout-ms 5000})]
+ (mt/with-dynamic-fn-redefs [config/config-int (with-config-overrides #'config/config-int
+ {:mb-application-db-checkout-timeout-ms 5000})]
(is (= 5000 (get (#'mdb.connection-pool-setup/application-db-connection-pool-props)
"checkoutTimeout")))))
(testing "checkoutTimeout of 0 (block forever) can be explicitly restored"
- (with-redefs [config/config-int (with-config-overrides config/config-int
- {:mb-application-db-checkout-timeout-ms 0})]
+ (mt/with-dynamic-fn-redefs [config/config-int (with-config-overrides #'config/config-int
+ {:mb-application-db-checkout-timeout-ms 0})]
(is (= 0 (get (#'mdb.connection-pool-setup/application-db-connection-pool-props)
"checkoutTimeout"))
"an operator must be able to opt back into the legacy wait-forever behavior"))))
(deftest application-db-unreturned-connection-timeout-aliasing-test
(testing "the _SECONDS-suffixed name takes precedence over the legacy unsuffixed name"
- (with-redefs [config/config-int (with-config-overrides config/config-int
- {:mb-application-db-unreturned-connection-timeout-seconds 42
- :mb-application-db-unreturned-connection-timeout 99})]
+ (mt/with-dynamic-fn-redefs [config/config-int (with-config-overrides #'config/config-int
+ {:mb-application-db-unreturned-connection-timeout-seconds 42
+ :mb-application-db-unreturned-connection-timeout 99})]
(is (= 42 (get (#'mdb.connection-pool-setup/application-db-connection-pool-props)
"unreturnedConnectionTimeout")))))
(testing "the legacy unsuffixed name still works when the _SECONDS-suffixed name is not set"
- (with-redefs [config/config-int (with-config-overrides config/config-int
- {:mb-application-db-unreturned-connection-timeout-seconds nil
- :mb-application-db-unreturned-connection-timeout 99})]
+ (mt/with-dynamic-fn-redefs [config/config-int (with-config-overrides #'config/config-int
+ {:mb-application-db-unreturned-connection-timeout-seconds nil
+ :mb-application-db-unreturned-connection-timeout 99})]
(is (= 99 (get (#'mdb.connection-pool-setup/application-db-connection-pool-props)
"unreturnedConnectionTimeout"))))))
@@ -206,6 +207,8 @@
(testing "For Postgres app DBs, we should be executing `DISCARD ALL` when checking in a connection to reset state including read-only"
(when (= (app-db/db-type) :postgres)
(let [connection* (promise)]
+ ;; c3p0 calls the ConnectionCustomizer on a pool thread, which doesn't inherit *local-redefs*
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [mdb.connection-pool-setup/on-check-in
(let [orig @#'mdb.connection-pool-setup/on-check-in]
(fn [^java.sql.Connection connection]
diff --git a/test/metabase/channel/email/messages_test.clj b/test/metabase/channel/email/messages_test.clj
index 5fe61c049dd..e6d4b990136 100644
--- a/test/metabase/channel/email/messages_test.clj
+++ b/test/metabase/channel/email/messages_test.clj
@@ -69,7 +69,7 @@
(testing "send email succeeds w/o retry"
(let [[hook state] (rt/retry-analytics-config-hook)]
(binding [retry/*test-time-config-hook* hook]
- (with-redefs [email/send-email! mt/fake-inbox-email-fn]
+ (mt/with-dynamic-fn-redefs [email/send-email! mt/fake-inbox-email-fn]
(mt/with-temporary-setting-values [email-smtp-host "fake_smtp_host"
email-smtp-port 587]
(mt/reset-inbox!)
@@ -79,7 +79,7 @@
(testing "send email fails b/c retry limit"
(let [[hook state] (rt/retry-analytics-config-hook {:max-retries 1})]
(binding [retry/*test-time-config-hook* hook]
- (with-redefs [email/send-email! (tu/works-after 2 mt/fake-inbox-email-fn)]
+ (mt/with-dynamic-fn-redefs [email/send-email! (tu/works-after 2 mt/fake-inbox-email-fn)]
(mt/with-temporary-setting-values [email-smtp-host "fake_smtp_host"
email-smtp-port 587]
(mt/reset-inbox!)
@@ -90,7 +90,7 @@
(testing "send email succeeds w/ retry"
(let [[hook state] (rt/retry-analytics-config-hook {:max-retries 1})]
(binding [retry/*test-time-config-hook* hook]
- (with-redefs [email/send-email! (tu/works-after 1 mt/fake-inbox-email-fn)]
+ (mt/with-dynamic-fn-redefs [email/send-email! (tu/works-after 1 mt/fake-inbox-email-fn)]
(mt/with-temporary-setting-values [email-smtp-host "fake_smtp_host"
email-smtp-port 587]
(mt/reset-inbox!)
diff --git a/test/metabase/channel/email_test.clj b/test/metabase/channel/email_test.clj
index e001f89a8bd..0d1e1ebf52c 100644
--- a/test/metabase/channel/email_test.clj
+++ b/test/metabase/channel/email_test.clj
@@ -75,6 +75,11 @@
(defn do-with-fake-inbox!
"Impl for `with-fake-inbox` macro; prefer using that rather than calling this directly."
[f]
+ ;; `with-redefs`, not a dynamic redef: shared helper with ~84 call sites, some of which block in
+ ;; `do-with-expected-messages` waiting on mail sent from other threads. Whether a dynamic redef reaches
+ ;; those senders is unverified. `metabase.test` imports `inbox` from this ns, so converting it would
+ ;; have to use the `dynamic-redefs/` alias, not `mt/`.
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [email/send-email! fake-inbox-email-fn]
(reset-inbox!)
(tu/with-temporary-setting-values [email-smtp-host "fake_smtp_host"
@@ -359,8 +364,8 @@
;; `send-message!` — `send-message-or-throw!` sends each recipient batch for its side effect and does not
;; return the message.
(let [sent (atom nil)]
- (with-redefs [email/send-email! (fn [credentials email-details]
- (reset! sent (mock-send-email! credentials email-details)))]
+ (dynamic-redefs/with-dynamic-fn-redefs [email/send-email! (fn [credentials email-details]
+ (reset! sent (mock-send-email! credentials email-details)))]
(let [basename "this-is-quite-long-and-has-non-Âſçïı-characters"
csv-file (temp-csv basename csv-contents)
params-with-problematic-file (-> params
@@ -526,8 +531,8 @@
(deftest send-message-or-throw!-splits-large-recipient-lists-test
(let [sent (atom [])]
- (with-redefs [email/send-email! (fn [_ email-details]
- (swap! sent conj (or (:to email-details) (:bcc email-details))))]
+ (dynamic-redefs/with-dynamic-fn-redefs [email/send-email! (fn [_ email-details]
+ (swap! sent conj (or (:to email-details) (:bcc email-details))))]
(tu/with-temporary-setting-values [email-smtp-host "fake_smtp_host"
email-smtp-port 587
email-max-recipients-per-message 2]
@@ -540,8 +545,8 @@
(is (every? #(<= (count %) 2) @sent) "no message exceeds the cap")
(is (= recipients (vec (mapcat identity @sent))) "every recipient is covered exactly once, in order")))))
(testing "with the cap unset, all recipients go in a single message (unchanged behavior)"
- (with-redefs [email/send-email! (fn [_ email-details]
- (swap! sent conj (or (:to email-details) (:bcc email-details))))]
+ (dynamic-redefs/with-dynamic-fn-redefs [email/send-email! (fn [_ email-details]
+ (swap! sent conj (or (:to email-details) (:bcc email-details))))]
(tu/with-temporary-setting-values [email-smtp-host "fake_smtp_host"
email-smtp-port 587
email-max-recipients-per-message nil]
diff --git a/test/metabase/cmd/core_test.clj b/test/metabase/cmd/core_test.clj
index bc5beae2333..7c8dc41ecdc 100644
--- a/test/metabase/cmd/core_test.clj
+++ b/test/metabase/cmd/core_test.clj
@@ -1,10 +1,11 @@
(ns metabase.cmd.core-test
(:require
[clojure.test :refer [are deftest is testing]]
- [metabase.cmd.core :as cmd]))
+ [metabase.cmd.core :as cmd]
+ [metabase.test.util.dynamic-redefs :as dynamic-redefs]))
(defn- do-with-captured-call-enterprise-calls! [thunk]
- (with-redefs [cmd/call-enterprise list]
+ (dynamic-redefs/with-dynamic-fn-redefs [cmd/call-enterprise list]
(thunk)))
(deftest ^:parallel error-message-test
diff --git a/test/metabase/cmd/remove_encryption_test.clj b/test/metabase/cmd/remove_encryption_test.clj
index aee9f91b175..c411147e2f4 100644
--- a/test/metabase/cmd/remove_encryption_test.clj
+++ b/test/metabase/cmd/remove_encryption_test.clj
@@ -28,8 +28,8 @@
:value))
(deftest cmd-remove-encryption-errors-when-failed-test
- (with-redefs [remove-encryption! #(throw (Exception. "err"))
- cmd/system-exit! identity]
+ (mt/with-dynamic-fn-redefs [remove-encryption! #(throw (Exception. "err"))
+ cmd/system-exit! identity]
(is (= 1 (cmd/remove-encryption)))))
(deftest remove-encryption!-test
diff --git a/test/metabase/cmd/rotate_encryption_key_test.clj b/test/metabase/cmd/rotate_encryption_key_test.clj
index ce90229c547..31b58c385a3 100644
--- a/test/metabase/cmd/rotate_encryption_key_test.clj
+++ b/test/metabase/cmd/rotate_encryption_key_test.clj
@@ -69,9 +69,9 @@
;; `database.details` use mi/transform-encrypted-json as transformation
;; the original definition of mi/transform-encrypted-json has a cached version of out transform
;; in this test we change they key multiple times and we don't want the value to be cached when key change
- (with-redefs [mi/transform-encrypted-json (fn [source]
- {:in mi/encrypted-json-in
- :out (mi/decrypt-error-context source mi/encrypted-json-out)})]
+ (mt/with-dynamic-fn-redefs [mi/transform-encrypted-json (fn [source]
+ {:in mi/encrypted-json-in
+ :out (mi/decrypt-error-context source mi/encrypted-json-out)})]
(binding [;; EXPLANATION FOR WHY THIS TEST WAS FLAKY
;; at this point, all the state switching craziness that happens for
;; `metabase.util.i18n.impl/site-locale-from-setting` has already taken place, so this function has
diff --git a/test/metabase/collections/create_test.clj b/test/metabase/collections/create_test.clj
index d425078bf06..bfb89619bd0 100644
--- a/test/metabase/collections/create_test.clj
+++ b/test/metabase/collections/create_test.clj
@@ -17,28 +17,28 @@
(deftest apply-defaults-to-collection-test
(testing "Child inherits :namespace from a non-default-namespace parent"
(mt/with-temp [:model/Collection parent {:name "Snippet Parent" :namespace "snippets"}]
- (with-redefs [api/write-check (fn [& _])]
+ (mt/with-dynamic-fn-redefs [api/write-check (fn [& _])]
(let [defaulted (collections.create/apply-defaults-to-collection
{:name "Snippet Child" :parent_id (:id parent)})]
(is (= :snippets (:namespace defaulted))
"Namespace propagates from parent when child doesn't specify one")))))
(testing "Caller's explicit :namespace wins over parent's"
(mt/with-temp [:model/Collection parent {:name "Snippet Parent 2" :namespace "snippets"}]
- (with-redefs [api/write-check (fn [& _])]
+ (mt/with-dynamic-fn-redefs [api/write-check (fn [& _])]
;; Caller-provided namespace overrides parent inheritance — REST behavior we mirror.
(let [defaulted (collections.create/apply-defaults-to-collection
{:name "Explicit NS Child" :parent_id (:id parent) :namespace "default"})]
(is (= "default" (:namespace defaulted)))))))
(testing "Child inherits :type from a library-typed parent"
(mt/with-temp [:model/Collection parent {:name "Library Parent" :type "library"}]
- (with-redefs [api/write-check (fn [& _])]
+ (mt/with-dynamic-fn-redefs [api/write-check (fn [& _])]
(let [defaulted (collections.create/apply-defaults-to-collection
{:name "Library Child" :parent_id (:id parent)})]
(is (= "library" (:type defaulted))
"Library type propagates so the child stays inside the library hierarchy")))))
(testing "Child does NOT inherit :type \"trash\" from a trash parent"
(mt/with-temp [:model/Collection parent {:name "Trashy Parent" :type "trash"}]
- (with-redefs [api/write-check (fn [& _])]
+ (mt/with-dynamic-fn-redefs [api/write-check (fn [& _])]
;; "trash" is a sentinel for the Trash collection; only library types propagate.
(let [defaulted (collections.create/apply-defaults-to-collection
{:name "Not-Trash Child" :parent_id (:id parent)})]
@@ -46,7 +46,7 @@
"Trash type does not propagate to children")))))
(testing "Child does NOT inherit :type \"tenant-specific-root-collection\" from a tenant root parent (UXW-4520)"
(mt/with-temp [:model/Collection parent {:name "Tenant Root" :type "tenant-specific-root-collection"}]
- (with-redefs [api/write-check (fn [& _])]
+ (mt/with-dynamic-fn-redefs [api/write-check (fn [& _])]
;; The tenant root type is a root-only sentinel; propagating it would fail the closed
;; output schema and break tenant sub-collection creation.
(let [defaulted (collections.create/apply-defaults-to-collection
@@ -55,14 +55,14 @@
"Tenant root type does not propagate to children")))))
(testing "Child inherits :is_remote_synced from a remote-synced parent"
(mt/with-temp [:model/Collection parent {:name "RS Parent" :is_remote_synced true}]
- (with-redefs [api/write-check (fn [& _])]
+ (mt/with-dynamic-fn-redefs [api/write-check (fn [& _])]
(let [defaulted (collections.create/apply-defaults-to-collection
{:name "RS Child" :parent_id (:id parent)})]
(is (true? (:is_remote_synced defaulted))
"Remote-synced flag propagates so the child participates in remote sync")))))
(testing "Plain parent: child gets is_remote_synced=false, no type, no namespace"
(mt/with-temp [:model/Collection parent {:name "Plain Parent"}]
- (with-redefs [api/write-check (fn [& _])]
+ (mt/with-dynamic-fn-redefs [api/write-check (fn [& _])]
(let [defaulted (collections.create/apply-defaults-to-collection
{:name "Plain Child" :parent_id (:id parent)})]
(is (false? (:is_remote_synced defaulted)))
@@ -70,7 +70,7 @@
(is (not (contains? defaulted :namespace)))))))
(testing "Location reflects parent path"
(mt/with-temp [:model/Collection parent {:name "Path Parent"}]
- (with-redefs [api/write-check (fn [& _])]
+ (mt/with-dynamic-fn-redefs [api/write-check (fn [& _])]
(let [defaulted (collections.create/apply-defaults-to-collection
{:name "Path Child" :parent_id (:id parent)})]
(is (= (str "/" (:id parent) "/") (:location defaulted))))))))
@@ -78,7 +78,7 @@
(deftest create-collection!-test
(testing "Creates a collection and persists inheritance defaults"
(mt/with-temp [:model/Collection parent {:name "Persist Parent" :is_remote_synced true}]
- (with-redefs [api/write-check (fn [& _])]
+ (mt/with-dynamic-fn-redefs [api/write-check (fn [& _])]
(let [coll (collections.create/create-collection!
{:name "Persist Child" :parent_id (:id parent)})]
(try
diff --git a/test/metabase/contextual_interestingness/core_test.clj b/test/metabase/contextual_interestingness/core_test.clj
index 287dabe9b43..cacba37e61c 100644
--- a/test/metabase/contextual_interestingness/core_test.clj
+++ b/test/metabase/contextual_interestingness/core_test.clj
@@ -9,6 +9,7 @@
[metabase.metabot.self :as metabot.self]
[metabase.metabot.settings :as metabot.settings]
[metabase.metabot.usage :as usage]
+ [metabase.test :as mt]
[metabase.util.log.capture :as log.capture]))
(def ^:private chart-config
@@ -25,10 +26,11 @@
(defn- with-llm-configured! [thunk]
;; the LLM gate checks usage limits and user permissions in addition to the settings,
;; so stub all four for tests that want the gate open.
- (with-redefs [metabot.settings/metabot-enabled? (constantly true)
- metabot.settings/llm-metabot-configured? (constantly true)
- usage/check-usage-limits! (constantly nil)
- scope/resolve-user-permissions (constantly scope/all-yes-permissions)]
+ (mt/with-dynamic-fn-redefs
+ [metabot.settings/metabot-enabled? (constantly true)
+ metabot.settings/llm-metabot-configured? (constantly true)
+ usage/check-usage-limits! (constantly nil)
+ scope/resolve-user-permissions (constantly scope/all-yes-permissions)]
(thunk)))
(defn- call
@@ -42,8 +44,9 @@
(deftest score-and-describe-blank-context-test
(testing "blank or nil context returns nil without invoking the LLM"
(let [calls (atom 0)]
- (with-redefs [metabot.self/call-llm-structured
- (fn [& _] (swap! calls inc) {:score 1.0 :chart_description "c" :reasoning "x"})]
+ (mt/with-dynamic-fn-redefs
+ [metabot.self/call-llm-structured
+ (fn [& _] (swap! calls inc) {:score 1.0 :chart_description "c" :reasoning "x"})]
(with-llm-configured!
(fn []
(is (nil? (call {:context-string nil})))
@@ -54,8 +57,9 @@
(deftest score-and-describe-nil-config-test
(testing "nil chart-config returns nil without invoking the LLM"
(let [calls (atom 0)]
- (with-redefs [metabot.self/call-llm-structured
- (fn [& _] (swap! calls inc) {:score 1.0 :chart_description "c" :reasoning "x"})]
+ (mt/with-dynamic-fn-redefs
+ [metabot.self/call-llm-structured
+ (fn [& _] (swap! calls inc) {:score 1.0 :chart_description "c" :reasoning "x"})]
(with-llm-configured!
(fn []
(is (nil? (call {:chart-config nil})))
@@ -64,9 +68,10 @@
(deftest score-and-describe-unconfigured-llm-test
(testing "returns nil and skips the LLM call when no provider is configured"
(let [calls (atom 0)]
- (with-redefs [metabot.settings/llm-metabot-configured? (constantly false)
- metabot.self/call-llm-structured
- (fn [& _] (swap! calls inc) {:score 1.0 :chart_description "c" :reasoning "x"})]
+ (mt/with-dynamic-fn-redefs
+ [metabot.settings/llm-metabot-configured? (constantly false)
+ metabot.self/call-llm-structured
+ (fn [& _] (swap! calls inc) {:score 1.0 :chart_description "c" :reasoning "x"})]
(is (nil? (call {})))
(is (zero? @calls))))))
@@ -112,11 +117,12 @@
(deftest score-and-describe-happy-path-test
(testing "valid LLM response returns score + descriptions; metric description is generated when card-description is blank"
- (with-redefs [metabot.self/call-llm-structured
- (constantly {:score 0.85
- :chart_description "Monthly revenue trend over the past year"
- :metric_description "Total monthly revenue from completed orders"
- :reasoning "directly addresses revenue trend"})]
+ (mt/with-dynamic-fn-redefs
+ [metabot.self/call-llm-structured
+ (constantly {:score 0.85
+ :chart_description "Monthly revenue trend over the past year"
+ :metric_description "Total monthly revenue from completed orders"
+ :reasoning "directly addresses revenue trend"})]
(with-llm-configured!
(fn []
(let [out (call {})]
@@ -126,10 +132,11 @@
(deftest score-and-describe-with-card-description-test
(testing "When card-description is provided, the schema does not require metric_description and parse-response surfaces it as nil"
- (with-redefs [metabot.self/call-llm-structured
- (constantly {:score 0.6
- :chart_description "Monthly revenue"
- :reasoning "related"})]
+ (mt/with-dynamic-fn-redefs
+ [metabot.self/call-llm-structured
+ (constantly {:score 0.6
+ :chart_description "Monthly revenue"
+ :reasoning "related"})]
(with-llm-configured!
(fn []
(let [out (call {:card-description "Sum of completed order totals"})]
@@ -141,31 +148,36 @@
(testing "scores outside [0,1] are clamped"
(with-llm-configured!
(fn []
- (with-redefs [metabot.self/call-llm-structured
- (constantly {:score 1.5 :chart_description "c" :reasoning "over"})]
+ (mt/with-dynamic-fn-redefs
+ [metabot.self/call-llm-structured
+ (constantly {:score 1.5 :chart_description "c" :reasoning "over"})]
(is (= 1.0 (:score (call {})))))
- (with-redefs [metabot.self/call-llm-structured
- (constantly {:score -0.2 :chart_description "c" :reasoning "under"})]
+ (mt/with-dynamic-fn-redefs
+ [metabot.self/call-llm-structured
+ (constantly {:score -0.2 :chart_description "c" :reasoning "under"})]
(is (= 0.0 (:score (call {})))))))))
(deftest score-and-describe-malformed-response-test
(testing "missing or non-numeric :score → nil (caller-visible failure mode)"
(with-llm-configured!
(fn []
- (with-redefs [metabot.self/call-llm-structured
- (constantly {:chart_description "c" :reasoning "no score"})]
+ (mt/with-dynamic-fn-redefs
+ [metabot.self/call-llm-structured
+ (constantly {:chart_description "c" :reasoning "no score"})]
(is (nil? (call {}))))
- (with-redefs [metabot.self/call-llm-structured
- (constantly {:score "not a number" :chart_description "c" :reasoning "wrong type"})]
+ (mt/with-dynamic-fn-redefs
+ [metabot.self/call-llm-structured
+ (constantly {:score "not a number" :chart_description "c" :reasoning "wrong type"})]
(is (nil? (call {}))))))))
(deftest score-and-describe-empty-descriptions-test
(testing "blank/whitespace descriptions parse to nil"
- (with-redefs [metabot.self/call-llm-structured
- (constantly {:score 0.5
- :chart_description " "
- :metric_description ""
- :reasoning "x"})]
+ (mt/with-dynamic-fn-redefs
+ [metabot.self/call-llm-structured
+ (constantly {:score 0.5
+ :chart_description " "
+ :metric_description ""
+ :reasoning "x"})]
(with-llm-configured!
(fn []
(let [out (call {})]
@@ -175,15 +187,17 @@
(deftest score-and-describe-llm-throws-test
(testing "transport / API errors are caught and surfaced as nil — never thrown"
- (with-redefs [metabot.self/call-llm-structured (fn [& _] (throw (ex-info "boom" {:status 503})))]
+ (mt/with-dynamic-fn-redefs
+ [metabot.self/call-llm-structured (fn [& _] (throw (ex-info "boom" {:status 503})))]
(with-llm-configured!
(fn []
(is (nil? (call {}))))))))
(deftest score-and-describe-llm-error-code-logged-test
(testing "a failure surfaces the ex-data :error-code in the warn log so nil scores are diagnosable"
- (with-redefs [metabot.self/call-llm-structured
- (fn [& _] (throw (ex-info "bad json" {:error-code "structured-output-invalid"})))]
+ (mt/with-dynamic-fn-redefs
+ [metabot.self/call-llm-structured
+ (fn [& _] (throw (ex-info "bad json" {:error-code "structured-output-invalid"})))]
(with-llm-configured!
(fn []
(let [msgs (log.capture/with-log-messages-for-level
@@ -206,8 +220,9 @@
(deftest score-and-describe-surfaces-reasoning-test
(testing "the LLM's reasoning flows all the way through to the public result map"
- (with-redefs [metabot.self/call-llm-structured
- (constantly {:score 0.7 :chart_description "c" :reasoning "because revenue"})]
+ (mt/with-dynamic-fn-redefs
+ [metabot.self/call-llm-structured
+ (constantly {:score 0.7 :chart_description "c" :reasoning "because revenue"})]
(with-llm-configured!
(fn []
(is (= "because revenue" (:reasoning (call {})))))))))
@@ -233,10 +248,11 @@
"Run the scorer with the LLM stubbed out and return the `messages` vector it was handed."
[overrides]
(let [captured (atom nil)]
- (with-redefs [metabot.self/call-llm-structured
- (fn [_model messages _schema _temp _max-tokens _opts]
- (reset! captured messages)
- {:score 0.7 :chart_description "c" :reasoning "x"})]
+ (mt/with-dynamic-fn-redefs
+ [metabot.self/call-llm-structured
+ (fn [_model messages _schema _temp _max-tokens _opts]
+ (reset! captured messages)
+ {:score 0.7 :chart_description "c" :reasoning "x"})]
(with-llm-configured! (fn [] (call overrides))))
@captured))
diff --git a/test/metabase/core/core_test.clj b/test/metabase/core/core_test.clj
index b6cd686efbe..6abfd9420f5 100644
--- a/test/metabase/core/core_test.clj
+++ b/test/metabase/core/core_test.clj
@@ -49,7 +49,7 @@
(testing "With no sample database present the bundled one is added, so fresh installs still get it"
(mt/with-temp-empty-app-db [_conn :h2]
(mdb/setup-db! :create-sample-content? false)
- (with-redefs [config/load-sample-content? (constantly true)]
+ (mt/with-dynamic-fn-redefs [config/load-sample-content? (constantly true)]
(#'core/reconcile-sample-database!))
(let [sample-db (t2/select-one :model/Database :is_sample true)]
(is (some? sample-db))
diff --git a/test/metabase/driver/sql_jdbc/connection_test.clj b/test/metabase/driver/sql_jdbc/connection_test.clj
index 2dca17107fe..6ad94ea2380 100644
--- a/test/metabase/driver/sql_jdbc/connection_test.clj
+++ b/test/metabase/driver/sql_jdbc/connection_test.clj
@@ -281,7 +281,7 @@
;; HACK: The ClickHouse driver also calls `db->pooled-connection-spec` to answer
;; `driver-supports? :connection-impersonation`. That perturbs the call count, so add a special case
;; to [[driver.u/supports?]].
- original-supports? driver.u/supports?
+ original-supports? (mt/original-fn #'driver.u/supports?)
supports?-fn (fn [driver feature database]
;; [kondo-keep] suppresses a warning :redundant-ignore can't see; --audit rechecks
(if (and #_{:clj-kondo/ignore [:metabase/disallow-hardcoded-driver-names-in-tests]}
@@ -291,8 +291,8 @@
(original-supports? driver feature database)))]
(try
(sql-jdbc.conn/invalidate-pool-for-db! db)
- (with-redefs [sql-jdbc.conn/log-jdbc-spec-hash-change-msg! hash-change-fn
- driver.u/supports? supports?-fn]
+ (mt/with-dynamic-fn-redefs [sql-jdbc.conn/log-jdbc-spec-hash-change-msg! hash-change-fn
+ driver.u/supports? supports?-fn]
(let [pool-spec-1 (sql-jdbc.conn/db->pooled-connection-spec db)
db-hash-1 (get @@#'sql-jdbc.conn/pool-cache-key->jdbc-spec-hash (#'sql-jdbc.conn/pool-cache-key db))]
(testing "hash value calculated correctly for new pooled conn"
diff --git a/test/metabase/driver/sql_jdbc/execute_test.clj b/test/metabase/driver/sql_jdbc/execute_test.clj
index 25e030ee6db..1815ea7f4b9 100644
--- a/test/metabase/driver/sql_jdbc/execute_test.clj
+++ b/test/metabase/driver/sql_jdbc/execute_test.clj
@@ -98,7 +98,7 @@
(identical? (get-method sql-jdbc.execute/do-with-connection-with-options :sql-jdbc)
(get-method sql-jdbc.execute/do-with-connection-with-options driver/*driver*))
- orig-do-with-resolved-connection-data-source @#'sql-jdbc.execute/do-with-resolved-connection-data-source
+ orig-do-with-resolved-connection-data-source (mt/original-fn #'sql-jdbc.execute/do-with-resolved-connection-data-source)
closed-conn (proxy [Connection] []
(isClosed [] true)
(close [] nil))
@@ -124,19 +124,18 @@
(vswap! connection-option-calls conj [:setHoldability holdability]))
(setNetworkTimeout [executor timeout-ms]
(vswap! connection-option-calls conj [:setNetworkTimeout timeout-ms])))]
- (with-redefs [sql-jdbc.execute/do-with-resolved-connection-data-source
- (fn [driver db options]
- (if (:keep-open? options)
- (reify javax.sql.DataSource
- (getConnection [_] new-conn))
- (orig-do-with-resolved-connection-data-source driver db options)))
-
- sql-jdbc.execute/recursive-connection?
- (let [original-recursive-fn sql-jdbc.execute/recursive-connection?]
- (fn []
- (let [ret (original-recursive-fn)]
- (vswap! connection-option-calls conj [:recursive-connection-check ret])
- ret)))]
+ (mt/with-dynamic-fn-redefs [sql-jdbc.execute/do-with-resolved-connection-data-source
+ (fn [driver db options]
+ (if (:keep-open? options)
+ (reify javax.sql.DataSource
+ (getConnection [_] new-conn))
+ (orig-do-with-resolved-connection-data-source driver db options)))
+ sql-jdbc.execute/recursive-connection?
+ (let [original-recursive-fn (mt/original-fn #'sql-jdbc.execute/recursive-connection?)]
+ (fn []
+ (let [ret (original-recursive-fn)]
+ (vswap! connection-option-calls conj [:recursive-connection-check ret])
+ ret)))]
(driver/do-with-resilient-connection
driver/*driver* (mt/id)
(fn [driver _db]
@@ -226,12 +225,12 @@
;; It's not straightforward to trigger a `.getConnection` error for some drivers (e.g. sqlite)
;; so just mock the exception. Also need to mock this h2 method so that the query doesn't fail
;; before it gets to `do-with-resolved-connection-data-source`.
- (with-redefs [h2/check-read-only-statements (fn [_query] nil)
- sql-jdbc.execute/do-with-resolved-connection-data-source
- (fn [_driver _db-or-id-or-spec _options]
- (reify javax.sql.DataSource
- (getConnection [_]
- (throw (java.sql.SQLException. "connection error")))))]
+ (mt/with-dynamic-fn-redefs [h2/check-read-only-statements (fn [_query] nil)
+ sql-jdbc.execute/do-with-resolved-connection-data-source
+ (fn [_driver _db-or-id-or-spec _options]
+ (reify javax.sql.DataSource
+ (getConnection [_]
+ (throw (java.sql.SQLException. "connection error")))))]
(let [query {:database (:id tmp-db)
:type :native
:native {:query "SELECT 1"}}
@@ -245,14 +244,14 @@
#_{:clj-kondo/ignore [:discouraged-var]}
(mt/with-temp [:model/Database tmp-db {:details (tx/bad-connection-details driver/*driver*)
:engine driver/*driver*}]
- (with-redefs [h2/check-read-only-statements (fn [_query] nil)
- sql-jdbc.execute/do-with-resolved-connection-data-source
- (fn [_driver _db-or-id-or-spec _options]
- (reify javax.sql.DataSource
- (getConnection [_]
- (throw (java.sql.SQLException.
- "An attempt by a client to checkout a Connection has timed out."
- (com.mchange.v2.resourcepool.TimeoutException. "timed out"))))))]
+ (mt/with-dynamic-fn-redefs [h2/check-read-only-statements (fn [_query] nil)
+ sql-jdbc.execute/do-with-resolved-connection-data-source
+ (fn [_driver _db-or-id-or-spec _options]
+ (reify javax.sql.DataSource
+ (getConnection [_]
+ (throw (java.sql.SQLException.
+ "An attempt by a client to checkout a Connection has timed out."
+ (com.mchange.v2.resourcepool.TimeoutException. "timed out"))))))]
(let [query {:database (:id tmp-db)
:type :native
:native {:query "SELECT 1"}}
@@ -284,12 +283,12 @@
(mt/with-temp [:model/Database tmp-db {:details (tx/bad-connection-details driver/*driver*)
:engine driver/*driver*}]
(mt/with-temporary-setting-values [jdbc-data-warehouse-connection-pool-max-pending-checkouts 1]
- (with-redefs [h2/check-read-only-statements (fn [_query] nil)
- sql-jdbc.execute/do-with-resolved-connection-data-source
- (fn [_driver _db-or-id-or-spec _options]
- ;; a pool that already has more queries waiting than the configured max
- (reify com.mchange.v2.c3p0.PooledDataSource
- (getNumThreadsAwaitingCheckoutDefaultUser [_] 5)))]
+ (mt/with-dynamic-fn-redefs [h2/check-read-only-statements (fn [_query] nil)
+ sql-jdbc.execute/do-with-resolved-connection-data-source
+ (fn [_driver _db-or-id-or-spec _options]
+ ;; a pool that already has more queries waiting than the configured max
+ (reify com.mchange.v2.c3p0.PooledDataSource
+ (getNumThreadsAwaitingCheckoutDefaultUser [_] 5)))]
(let [query {:database (:id tmp-db)
:type :native
:native {:query "SELECT 1"}}
diff --git a/test/metabase/driver/sql_jdbc_test.clj b/test/metabase/driver/sql_jdbc_test.clj
index 5bcfb95d9bc..ceeae671932 100644
--- a/test/metabase/driver/sql_jdbc_test.clj
+++ b/test/metabase/driver/sql_jdbc_test.clj
@@ -200,11 +200,11 @@
:+features [:actions]
:+conn-props ["schema-filters"]})
(let [fake-schema-name (u/qualified-name ::fake-schema)]
- (with-redefs [sql-jdbc.describe-database/all-schemas (let [orig sql-jdbc.describe-database/all-schemas]
- (fn [metadata]
- (eduction
- cat
- [(orig metadata) [fake-schema-name]])))]
+ (mt/with-dynamic-fn-redefs [sql-jdbc.describe-database/all-schemas (let [orig (mt/original-fn #'sql-jdbc.describe-database/all-schemas)]
+ (fn [metadata]
+ (eduction
+ cat
+ [(orig metadata) [fake-schema-name]])))]
(let [syncable (driver/syncable-schemas driver/*driver* (mt/db))]
(is (contains? syncable "public"))
(is (contains? syncable fake-schema-name))))
diff --git a/test/metabase/explorations/impl_test.clj b/test/metabase/explorations/impl_test.clj
index a257bdd1379..51228cee065 100644
--- a/test/metabase/explorations/impl_test.clj
+++ b/test/metabase/explorations/impl_test.clj
@@ -77,7 +77,7 @@
(testing "resolver computes breakoutable-columns once per (db,table) and reuses it"
(let [calls (atom 0)
resolve* (make-resolver)]
- (with-redefs [lib/breakoutable-columns (fn [_] (swap! calls inc) [])]
+ (mt/with-dynamic-fn-redefs [lib/breakoutable-columns (fn [_] (swap! calls inc) [])]
(resolve* m q) ; orders: miss
(resolve* m q) ; orders: hit
(resolve* (assoc m :table_id (mt/id :products)) q)) ; products: miss
diff --git a/test/metabase/explorations/query_plan/variants_test.clj b/test/metabase/explorations/query_plan/variants_test.clj
index a801162aaed..682bf5cac54 100644
--- a/test/metabase/explorations/query_plan/variants_test.clj
+++ b/test/metabase/explorations/query_plan/variants_test.clj
@@ -310,10 +310,10 @@
(request/with-current-user user-id
(#'variants/cached-discovery ctx)))
calls (atom 0)
- real @#'variants/run-top-k-discovery]
- (with-redefs [variants/run-top-k-discovery (fn [& args]
- (swap! calls inc)
- (apply real args))]
+ real (mt/original-fn #'variants/run-top-k-discovery)]
+ (mt/with-dynamic-fn-redefs [variants/run-top-k-discovery (fn [& args]
+ (swap! calls inc)
+ (apply real args))]
(discover (mt/user->id :rasta))
(discover (mt/user->id :crowberto))
(is (= 2 @calls)
diff --git a/test/metabase/mcp/v2/dashboard_ops_test.clj b/test/metabase/mcp/v2/dashboard_ops_test.clj
index f0547d8515b..ce2e3079415 100644
--- a/test/metabase/mcp/v2/dashboard_ops_test.clj
+++ b/test/metabase/mcp/v2/dashboard_ops_test.clj
@@ -5,7 +5,8 @@
(:require
[clojure.test :refer :all]
[metabase.mcp.v2.dashboard-ops :as dashboard-ops]
- [metabase.parameters.mapping-targets]))
+ [metabase.parameters.mapping-targets]
+ [metabase.test.util.dynamic-redefs :as dynamic-redefs]))
(set! *warn-on-reflection* true)
@@ -636,9 +637,9 @@
(let [current {:id 1 :tabs [] :parameters [{:id "p1" :name "Cat" :type "string/="}]
:dashcards [{:id 7 :card_id 9 :row 0 :col 0 :size_x 4 :size_y 4
:parameter_mappings []}]}
- {:keys [dashcards]} (with-redefs [metabase.parameters.mapping-targets/target-for-field
- (fn [_card _param field-id]
- [:dimension [:field field-id nil]])]
+ {:keys [dashcards]} (dynamic-redefs/with-dynamic-fn-redefs [metabase.parameters.mapping-targets/target-for-field
+ (fn [_card _param field-id]
+ [:dimension [:field field-id nil]])]
(dashboard-ops/compile-ops
current
[{:op "wire_parameter" :parameter_id "p1" :dashcard_id 7 :target_field 55}]
@@ -652,9 +653,9 @@
(let [current {:id 1 :tabs [] :parameters [{:id "p1" :name "Cat" :type "string/="}]
:dashcards [{:id 7 :card_id 9 :row 0 :col 0 :size_x 4 :size_y 4
:parameter_mappings []}]}
- {:keys [dashcards]} (with-redefs [metabase.parameters.mapping-targets/target-for-field
- (fn [_card _param field-id]
- [:dimension [:field field-id nil]])]
+ {:keys [dashcards]} (dynamic-redefs/with-dynamic-fn-redefs [metabase.parameters.mapping-targets/target-for-field
+ (fn [_card _param field-id]
+ [:dimension [:field field-id nil]])]
(dashboard-ops/compile-ops
current
[{:op "wire_parameter" :parameter_id "p1" :dashcard_id 7 :target_field 55}
@@ -669,7 +670,7 @@
:dashcards [{:id 7 :card_id 9 :row 0 :col 0 :size_x 4 :size_y 4 :parameter_mappings []}]}]
(is (thrown-with-msg?
clojure.lang.ExceptionInfo #"op 0.*wire_parameter"
- (with-redefs [metabase.parameters.mapping-targets/target-for-field (constantly nil)]
+ (dynamic-redefs/with-dynamic-fn-redefs [metabase.parameters.mapping-targets/target-for-field (constantly nil)]
(dashboard-ops/compile-ops
current
[{:op "wire_parameter" :parameter_id "p1" :dashcard_id 7 :target_field 55}]
@@ -690,9 +691,9 @@
(let [current {:id 1 :tabs [] :parameters [{:id "p1" :name "Cat" :type "string/="}]
:dashcards [{:id 7 :card_id 9 :row 0 :col 0 :size_x 4 :size_y 4 :parameter_mappings []}
{:id 8 :card_id 10 :row 4 :col 0 :size_x 4 :size_y 4 :parameter_mappings []}]}
- {:keys [dashcards]} (with-redefs [metabase.parameters.mapping-targets/target-for-field
- (fn [card _param field-id]
- (when (= 9 (:id card)) [:dimension [:field field-id nil]]))]
+ {:keys [dashcards]} (dynamic-redefs/with-dynamic-fn-redefs [metabase.parameters.mapping-targets/target-for-field
+ (fn [card _param field-id]
+ (when (= 9 (:id card)) [:dimension [:field field-id nil]]))]
(dashboard-ops/compile-ops
current
[{:op "wire_parameter" :parameter_id "p1" :dashcard_id 7
diff --git a/test/metabase/mcp/v2/tools/parameters_test.clj b/test/metabase/mcp/v2/tools/parameters_test.clj
index 798990001b8..f2c80a8fcca 100644
--- a/test/metabase/mcp/v2/tools/parameters_test.clj
+++ b/test/metabase/mcp/v2/tools/parameters_test.clj
@@ -785,8 +785,8 @@
the fetch actually failed (the dashboard path re-throws; the question path must not diverge)"
(do-with-people-name-card!
(fn [card-id]
- (with-redefs [search-values-query/search-values-query
- (fn [& _] (throw (ex-info "simulated warehouse timeout" {:simulated true})))]
+ (mt/with-dynamic-fn-redefs [search-values-query/search-values-query
+ (fn [& _] (throw (ex-info "simulated warehouse timeout" {:simulated true})))]
(let [error (params-error {:target "question" :id card-id :parameter_id "_PN_"})]
(is (re-find #"[Ee]rror" error) "the failure is reported as an error")
(is (not (re-find #"No values available" error))
diff --git a/test/metabase/mcp/v2/tools/search_test.clj b/test/metabase/mcp/v2/tools/search_test.clj
index c439e36dd51..d7550716f4f 100644
--- a/test/metabase/mcp/v2/tools/search_test.clj
+++ b/test/metabase/mcp/v2/tools/search_test.clj
@@ -411,7 +411,7 @@
(testing "GHY-4137: engine-results reports the engine's total for every search, including a
superuser transform search — transforms are no longer dropped by a post-filter, so
the total is accurate and is not suppressed"
- (with-redefs [metabot.search/search (fn [_ctx] (with-meta [{:id 1 :type "question"}] {:total 30}))]
+ (mt/with-dynamic-fn-redefs [metabot.search/search (fn [_ctx] (with-meta [{:id 1 :type "question"}] {:total 30}))]
(mt/with-test-user :crowberto
(is (= 30 (:total (engine-results {} ["question" "transform"] nil 20 0))))
(is (= 30 (:total (engine-results {} ["question" "dashboard"] nil 20 0))))))))
@@ -545,10 +545,10 @@
(testing "created_by: \"me\" with no type reaches the engine with the narrowed types, returns
results, and discloses the narrowing"
(let [captured-entity-types (atom nil)]
- (with-redefs [metabot.search/search (fn [{:keys [entity-types]}]
- (reset! captured-entity-types entity-types)
- (with-meta [{:id 1 :type "question" :name "My I5 Card"}]
- {:total 1}))]
+ (mt/with-dynamic-fn-redefs [metabot.search/search (fn [{:keys [entity-types]}]
+ (reset! captured-entity-types entity-types)
+ (with-meta [{:id 1 :type "question" :name "My I5 Card"}]
+ {:total 1}))]
(mt/with-current-user (mt/user->id :rasta)
(let [content (tools.search/search-tool {:term_queries ["I5"] :created_by "me"}
{:token-scopes #{"agent:content:read"}})
@@ -562,9 +562,9 @@
"the narrowing is disclosed in the response text"))))))
(testing "collection_id with no type reaches the engine with the narrowed types and discloses it"
(let [captured-entity-types (atom nil)]
- (with-redefs [metabot.search/search (fn [{:keys [entity-types]}]
- (reset! captured-entity-types entity-types)
- (with-meta [] {:total 0}))]
+ (mt/with-dynamic-fn-redefs [metabot.search/search (fn [{:keys [entity-types]}]
+ (reset! captured-entity-types entity-types)
+ (with-meta [] {:total 0}))]
(mt/with-temp [:model/Collection {coll-id :id} {}]
(mt/with-current-user (mt/user->id :crowberto)
(let [content (tools.search/search-tool {:term_queries ["I5"] :collection_id coll-id}
@@ -577,9 +577,9 @@
(is (re-find #"collection_id narrowed the search to" text))))))))
(testing "archived: true with no type reaches the engine with the narrowed types, does not 400"
(let [captured-entity-types (atom nil)]
- (with-redefs [metabot.search/search (fn [{:keys [entity-types]}]
- (reset! captured-entity-types entity-types)
- (with-meta [] {:total 0}))]
+ (mt/with-dynamic-fn-redefs [metabot.search/search (fn [{:keys [entity-types]}]
+ (reset! captured-entity-types entity-types)
+ (with-meta [] {:total 0}))]
(mt/with-current-user (mt/user->id :crowberto)
(let [content (tools.search/search-tool {:term_queries ["x"] :archived true}
{:token-scopes #{"agent:content:read"}})
diff --git a/test/metabase/metabot/api/metabot_test.clj b/test/metabase/metabot/api/metabot_test.clj
index 83b1c6d406d..16b2cf1a80e 100644
--- a/test/metabase/metabot/api/metabot_test.clj
+++ b/test/metabase/metabot/api/metabot_test.clj
@@ -68,8 +68,9 @@
:tables :table_questions})))]
;; --------------------------- Generating sample prompts ---------------------------
(testing "should generate prompt suggestions for metabot"
- (let [response (with-redefs [metabot.example-question-generator/generate-example-questions
- prompt-generator]
+ (let [response (mt/with-dynamic-fn-redefs
+ [metabot.example-question-generator/generate-example-questions
+ prompt-generator]
;; Trigger prompt generation by calling the regenerate endpoint
(mt/user-http-request
:crowberto :post 200
@@ -151,7 +152,8 @@
(mt/user-http-request :rasta :post 403 url)
(is (= remaining-prompt-ids (current-prompt-ids))))
(testing "admin users are allowed"
- (with-redefs [metabot.example-question-generator/generate-example-questions prompt-generator]
+ (mt/with-dynamic-fn-redefs
+ [metabot.example-question-generator/generate-example-questions prompt-generator]
(is (=? {:status "generated" :prompt_count pos-int?}
(mt/user-http-request :crowberto :post 200 url)))))))
(let [new-prompt-ids (current-prompt-ids)]
diff --git a/test/metabase/metabot/api_test.clj b/test/metabase/metabot/api_test.clj
index 6fbea809f09..9c37fe2bccd 100644
--- a/test/metabase/metabot/api_test.clj
+++ b/test/metabase/metabot/api_test.clj
@@ -139,18 +139,19 @@
(mt/with-temp [:model/MetabotConversation {conversation-id :id} {:user_id (mt/user->id :rasta)}]
(let [generate-title! #(#'conversation-title/generate! conversation-id "default" "Show orders by month")
stored-title #(t2/select-one-fn :title :model/MetabotConversation :id conversation-id)]
- (with-redefs [metabot.self/call-llm-structured (constantly {:title "\"Orders by Month!\""})]
+ (mt/with-dynamic-fn-redefs [metabot.self/call-llm-structured (constantly {:title "\"Orders by Month!\""})]
(is (= "Orders by Month" (generate-title!)))
(is (= "Orders by Month" (stored-title))))
- (with-redefs [metabot.self/call-llm-structured (constantly {:title "Different title"})]
+ (mt/with-dynamic-fn-redefs [metabot.self/call-llm-structured (constantly {:title "Different title"})]
(is (nil? (generate-title!)))
(is (= "Orders by Month" (stored-title)))))))
(deftest conversation-title-generation-skips-existing-title-test
(mt/with-temp [:model/MetabotConversation {conversation-id :id} {:user_id (mt/user->id :rasta)
:title "Existing Title"}]
- (with-redefs [metabot.self/call-llm-structured (fn [& _]
- (throw (ex-info "should not generate" {})))]
+ (mt/with-dynamic-fn-redefs
+ [metabot.self/call-llm-structured (fn [& _]
+ (throw (ex-info "should not generate" {})))]
(is (= {:status :ready :title "Existing Title"}
(conversation-title/ensure-title! conversation-id "default" "Show orders by month")))
(is (= {:status "ready" :title "Existing Title"}
@@ -160,10 +161,11 @@
(mt/with-temp [:model/MetabotConversation {conversation-id :id} {:user_id (mt/user->id :rasta)}]
(let [gate (promise)
call-count (atom 0)]
- (with-redefs [metabot.self/call-llm-structured (fn [& _]
- (swap! call-count inc)
- @gate
- {:title "Recovered Title"})]
+ (mt/with-dynamic-fn-redefs
+ [metabot.self/call-llm-structured (fn [& _]
+ (swap! call-count inc)
+ @gate
+ {:title "Recovered Title"})]
(let [future-1 (conversation-title/submit! conversation-id "default" "Show orders by month")
future-2 (conversation-title/submit! conversation-id "default" "Use a different prompt")]
(is (some? future-1))
@@ -314,18 +316,19 @@
(binding [scope/*current-user-metabot-permissions* scope/all-yes-permissions]
(let [stored-parts (atom nil)
stored-kwargs (atom nil)]
- (with-redefs [;; Pre-reducible throw: this is the exact escape path the new
- ;; catch covers. The agent loop's own (catch Exception) is
- ;; inside the reify, so a throw from `run-agent-loop` itself
- ;; bypasses it entirely.
- agent/run-agent-loop
- (fn [_opts]
- (throw (ex-info "agent setup exploded"
- {:status 503 :provider :test})))
- metabot.persistence/finalize-assistant-turn!
- (fn [_pk parts & kwargs]
- (reset! stored-parts parts)
- (reset! stored-kwargs (apply hash-map kwargs)))]
+ (mt/with-dynamic-fn-redefs
+ [;; Pre-reducible throw: this is the exact escape path the new
+ ;; catch covers. The agent loop's own (catch Exception) is
+ ;; inside the reify, so a throw from `run-agent-loop` itself
+ ;; bypasses it entirely.
+ agent/run-agent-loop
+ (fn [_opts]
+ (throw (ex-info "agent setup exploded"
+ {:status 503 :provider :test})))
+ metabot.persistence/finalize-assistant-turn!
+ (fn [_pk parts & kwargs]
+ (reset! stored-parts parts)
+ (reset! stored-kwargs (apply hash-map kwargs)))]
(mt/with-model-cleanup [:model/MetabotMessage
[:model/MetabotConversation :created_at]]
(let [response (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
@@ -783,9 +786,10 @@
(let [title-requests (atom [])]
(with-mock-streaming-provider!
(fn []
- (with-redefs [conversation-title/ensure-title! (fn [& args]
- (swap! title-requests conj args)
- {:status :missing})]
+ (mt/with-dynamic-fn-redefs
+ [conversation-title/ensure-title! (fn [& args]
+ (swap! title-requests conj args)
+ {:status :missing})]
(let [conversation-id (str (random-uuid))
first-response (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
(agent-request conversation-id "first prompt"))
@@ -831,18 +835,19 @@
turn-states (atom [{:queries {"q_1" {:database 1}} :todos [{:id "a" :status "pending"}]}
{:queries {"q_1" {:database 1} "q_2" {:database 2}} :todos [{:id "b" :status "done"}]}
nil])]
- (with-redefs [agent/run-agent-loop
- (fn [{:keys [state memory-atom]}]
- (swap! seeded-states conj state)
- (let [[turn-state] @turn-states]
- (swap! turn-states subvec 1)
- ;; mirror the real loop: populate the caller's atom so
- ;; finalize can persist this turn's state
- (some-> memory-atom
- (reset! {:turn-state (or turn-state {})}))
- (cond-> [{:type :start :id "msg-1"}
- {:type :text :text "ok"}]
- turn-state (conj {:type :data :data-type "state" :data turn-state}))))]
+ (mt/with-dynamic-fn-redefs
+ [agent/run-agent-loop
+ (fn [{:keys [state memory-atom]}]
+ (swap! seeded-states conj state)
+ (let [[turn-state] @turn-states]
+ (swap! turn-states subvec 1)
+ ;; mirror the real loop: populate the caller's atom so
+ ;; finalize can persist this turn's state
+ (some-> memory-atom
+ (reset! {:turn-state (or turn-state {})}))
+ (cond-> [{:type :start :id "msg-1"}
+ {:type :text :text "ok"}]
+ turn-state (conj {:type :data :data-type "state" :data turn-state}))))]
(mt/with-model-cleanup [:model/MetabotMessage [:model/MetabotConversation :created_at]]
(let [conversation-id (str (random-uuid))
turn-1-state {:queries {:q_1 {:database 1}} :todos [{:id "a" :status "pending"}]}
diff --git a/test/metabase/metabot/native_generation_integration_test.clj b/test/metabase/metabot/native_generation_integration_test.clj
index 25b31b323c7..d0b22c38a65 100644
--- a/test/metabase/metabot/native_generation_integration_test.clj
+++ b/test/metabase/metabot/native_generation_integration_test.clj
@@ -46,7 +46,7 @@
"NativeMetric1" ["native m1" "native m2" "native m3" "native m4" "native m5"]}
native-mock (make-native-prompt-generator prompts-by-name)]
(testing "regenerate endpoint works with native path"
- (with-redefs [native-generator/generate-example-questions native-mock]
+ (mt/with-dynamic-fn-redefs [native-generator/generate-example-questions native-mock]
(is (=? {:status "generated" :prompt_count 10}
(mt/user-http-request :crowberto :post 200
(format "metabot/metabot/%d/prompt-suggestions/regenerate" metabot-id)))))
@@ -61,7 +61,7 @@
(set (map :model prompts))))))
(testing "native path prompts are replaced on re-regenerate"
(let [old-ids (t2/select-pks-set :model/MetabotPrompt :metabot_id metabot-id)]
- (with-redefs [native-generator/generate-example-questions native-mock]
+ (mt/with-dynamic-fn-redefs [native-generator/generate-example-questions native-mock]
(is (=? {:status "generated" :prompt_count 10}
(mt/user-http-request :crowberto :post 200
(format "metabot/metabot/%d/prompt-suggestions/regenerate" metabot-id)))))
diff --git a/test/metabase/metabot/persistence_test.clj b/test/metabase/metabot/persistence_test.clj
index 079702db5ff..5e5e89f2ee7 100644
--- a/test/metabase/metabot/persistence_test.clj
+++ b/test/metabase/metabot/persistence_test.clj
@@ -1042,7 +1042,7 @@
valid JSON. Without this, an unusual ex-data value would fail the
whole UPDATE and the row would stay with error=nil — looking like
a clean success."
- (let [real-encode json/encode
+ (let [real-encode (mt/original-fn #'json/encode)
;; Simulate an encoder that chokes on a specific marker value, but
;; otherwise behaves normally — so the fallback's *second* encode call
;; (with :data swapped for pr-str) still succeeds.
@@ -1053,7 +1053,7 @@
(= ::poison (some-> v :data :marker)))
(throw (ex-info "simulated encoder failure" {}))
(if opts (real-encode v opts) (real-encode v)))))]
- (with-redefs [json/encode fail-encode]
+ (mt/with-dynamic-fn-redefs [json/encode fail-encode]
(let [encoded (#'metabot-persistence/safe-encode-error
{:message "wrapper"
:type "java.lang.RuntimeException"
diff --git a/test/metabase/metabot/self_test.clj b/test/metabase/metabot/self_test.clj
index be129102a3e..f9ec4abfb2c 100644
--- a/test/metabase/metabot/self_test.clj
+++ b/test/metabase/metabot/self_test.clj
@@ -1635,10 +1635,11 @@
(testing "When check-usage-limits! returns a message, the call throws an ex-info with
:type :metabot/usage-limit-reached *before* hitting the provider adapter."
(let [adapter-calls (atom 0)]
- (with-redefs [usage/check-usage-limits!
- (fn [] "you've used all of your AI tokens")
- self.claude/claude
- (fn [& _] (swap! adapter-calls inc) [])]
+ (mt/with-dynamic-fn-redefs
+ [usage/check-usage-limits!
+ (fn [] "you've used all of your AI tokens")
+ self.claude/claude
+ (fn [& _] (swap! adapter-calls inc) [])]
(let [ex (try-structured-call {})]
(is (= :metabot/usage-limit-reached (:type (ex-data ex))))
(is (= "ai_usage_limit_reached" (:error-code (ex-data ex))))
@@ -1649,14 +1650,15 @@
(testing ":required-permission is checked against the caller's metabot perms; a missing
grant throws :metabot/permission-denied before the provider adapter is hit."
(let [adapter-calls (atom 0)]
- (with-redefs [usage/check-usage-limits! (constantly nil)
- scope/resolve-user-permissions
- (fn [_uid] {:permission/metabot :yes
- :permission/metabot-sql-generation :yes
- :permission/metabot-nlq :yes
- :permission/metabot-other-tools :no})
- self.claude/claude
- (fn [& _] (swap! adapter-calls inc) [])]
+ (mt/with-dynamic-fn-redefs
+ [usage/check-usage-limits! (constantly nil)
+ scope/resolve-user-permissions
+ (fn [_uid] {:permission/metabot :yes
+ :permission/metabot-sql-generation :yes
+ :permission/metabot-nlq :yes
+ :permission/metabot-other-tools :no})
+ self.claude/claude
+ (fn [& _] (swap! adapter-calls inc) [])]
(let [ex (try-structured-call {:required-permission :permission/metabot-other-tools})]
(is (= :metabot/permission-denied (:type (ex-data ex))))
(is (= :permission/metabot-other-tools (:required-permission (ex-data ex))))
@@ -1665,12 +1667,13 @@
(deftest call-llm-structured-with-trace-throws-on-base-permission-denied-test
(testing "When `:required-permission` is set but the base :permission/metabot is denied,
the call throws with :required-permission :permission/metabot."
- (with-redefs [usage/check-usage-limits! (constantly nil)
- scope/resolve-user-permissions
- (fn [_uid] {:permission/metabot :no
- :permission/metabot-sql-generation :yes
- :permission/metabot-nlq :yes
- :permission/metabot-other-tools :yes})]
+ (mt/with-dynamic-fn-redefs
+ [usage/check-usage-limits! (constantly nil)
+ scope/resolve-user-permissions
+ (fn [_uid] {:permission/metabot :no
+ :permission/metabot-sql-generation :yes
+ :permission/metabot-nlq :yes
+ :permission/metabot-other-tools :yes})]
(let [ex (try-structured-call {:required-permission :permission/metabot-other-tools})]
(is (= :metabot/permission-denied (:type (ex-data ex))))
(is (= :permission/metabot (:required-permission (ex-data ex)))
@@ -1681,16 +1684,17 @@
Granting the base perm lets the call proceed to the adapter."
(let [resolve-calls (atom 0)
adapter-calls (atom 0)]
- (with-redefs [usage/check-usage-limits! (constantly nil)
- scope/resolve-user-permissions
- (fn [_uid]
- (swap! resolve-calls inc)
- {:permission/metabot :yes})
- ;; Throw inside the adapter so we don't depend on parts-shape details —
- ;; we just want to verify the base perm check passed and the call
- ;; reached the provider.
- self.claude/claude
- (fn [& _] (swap! adapter-calls inc) (throw (ex-info "adapter reached" {})))]
+ (mt/with-dynamic-fn-redefs
+ [usage/check-usage-limits! (constantly nil)
+ scope/resolve-user-permissions
+ (fn [_uid]
+ (swap! resolve-calls inc)
+ {:permission/metabot :yes})
+ ;; Throw inside the adapter so we don't depend on parts-shape details —
+ ;; we just want to verify the base perm check passed and the call
+ ;; reached the provider.
+ self.claude/claude
+ (fn [& _] (swap! adapter-calls inc) (throw (ex-info "adapter reached" {})))]
(try-structured-call {})
(is (pos? @resolve-calls)
"the base :permission/metabot check resolves perms even when no :required-permission is set")
@@ -1701,11 +1705,12 @@
(testing "Without `:required-permission`, the base :permission/metabot is still enforced;
a denial throws :metabot/permission-denied."
(let [adapter-calls (atom 0)]
- (with-redefs [usage/check-usage-limits! (constantly nil)
- scope/resolve-user-permissions
- (fn [_uid] {:permission/metabot :no})
- self.claude/claude
- (fn [& _] (swap! adapter-calls inc) [])]
+ (mt/with-dynamic-fn-redefs
+ [usage/check-usage-limits! (constantly nil)
+ scope/resolve-user-permissions
+ (fn [_uid] {:permission/metabot :no})
+ self.claude/claude
+ (fn [& _] (swap! adapter-calls inc) [])]
(let [ex (try-structured-call {})]
(is (= :metabot/permission-denied (:type (ex-data ex))))
(is (= :permission/metabot (:required-permission (ex-data ex))))
@@ -1716,10 +1721,11 @@
that yields a single :error part with error-code ai_usage_limit_reached
and never opens the provider stream."
(let [adapter-calls (atom 0)]
- (with-redefs [usage/check-usage-limits!
- (fn [] "you've used all of your AI tokens")
- self.claude/claude
- (fn [& _] (swap! adapter-calls inc) [])]
+ (mt/with-dynamic-fn-redefs
+ [usage/check-usage-limits!
+ (fn [] "you've used all of your AI tokens")
+ self.claude/claude
+ (fn [& _] (swap! adapter-calls inc) [])]
(let [parts (into [] (self/call-llm "anthropic/claude-haiku-4-5"
nil [] {} {} nil))]
(is (= 1 (count parts)))
@@ -1732,14 +1738,15 @@
grant yields a single :error part with error-code permission_denied,
without opening the provider stream."
(let [adapter-calls (atom 0)]
- (with-redefs [usage/check-usage-limits! (constantly nil)
- scope/resolve-user-permissions
- (fn [_uid] {:permission/metabot :yes
- :permission/metabot-sql-generation :yes
- :permission/metabot-nlq :yes
- :permission/metabot-other-tools :no})
- self.claude/claude
- (fn [& _] (swap! adapter-calls inc) [])]
+ (mt/with-dynamic-fn-redefs
+ [usage/check-usage-limits! (constantly nil)
+ scope/resolve-user-permissions
+ (fn [_uid] {:permission/metabot :yes
+ :permission/metabot-sql-generation :yes
+ :permission/metabot-nlq :yes
+ :permission/metabot-other-tools :no})
+ self.claude/claude
+ (fn [& _] (swap! adapter-calls inc) [])]
(let [parts (into [] (self/call-llm "anthropic/claude-haiku-4-5"
nil [] {}
{:required-permission :permission/metabot-other-tools}
@@ -1754,39 +1761,44 @@
(deftest llm-call-unavailable-reason-test
(let [perm :permission/metabot-other-tools]
(testing "nil (and llm-call-available? true) when every check passes"
- (with-redefs [metabot.settings/metabot-enabled? (constantly true)
- metabot.settings/llm-metabot-configured? (constantly true)
- usage/check-usage-limits! (constantly nil)
- scope/resolve-user-permissions (constantly scope/all-yes-permissions)]
+ (mt/with-dynamic-fn-redefs
+ [metabot.settings/metabot-enabled? (constantly true)
+ metabot.settings/llm-metabot-configured? (constantly true)
+ usage/check-usage-limits! (constantly nil)
+ scope/resolve-user-permissions (constantly scope/all-yes-permissions)]
(is (nil? (self/llm-call-unavailable-reason perm)))
(is (true? (self/llm-call-available? perm)))))
(testing ":metabot-disabled when Metabot is off"
- (with-redefs [metabot.settings/metabot-enabled? (constantly false)]
+ (mt/with-dynamic-fn-redefs [metabot.settings/metabot-enabled? (constantly false)]
(is (= :metabot-disabled (self/llm-call-unavailable-reason perm)))
(is (false? (self/llm-call-available? perm)))))
(testing ":no-llm when no provider is configured"
- (with-redefs [metabot.settings/metabot-enabled? (constantly true)
- metabot.settings/llm-metabot-configured? (constantly false)]
+ (mt/with-dynamic-fn-redefs
+ [metabot.settings/metabot-enabled? (constantly true)
+ metabot.settings/llm-metabot-configured? (constantly false)]
(is (= :no-llm (self/llm-call-unavailable-reason perm)))))
(testing ":usage-limit when over the AI usage limit"
- (with-redefs [metabot.settings/metabot-enabled? (constantly true)
- metabot.settings/llm-metabot-configured? (constantly true)
- usage/check-usage-limits! (constantly "You've used all your tokens")]
+ (mt/with-dynamic-fn-redefs
+ [metabot.settings/metabot-enabled? (constantly true)
+ metabot.settings/llm-metabot-configured? (constantly true)
+ usage/check-usage-limits! (constantly "You've used all your tokens")]
(is (= :usage-limit (self/llm-call-unavailable-reason perm)))))
(testing ":permission-denied when the current user lacks the required permission"
- (with-redefs [metabot.settings/metabot-enabled? (constantly true)
- metabot.settings/llm-metabot-configured? (constantly true)
- usage/check-usage-limits! (constantly nil)
- scope/resolve-user-permissions (constantly (assoc scope/all-yes-permissions
- perm :no))]
+ (mt/with-dynamic-fn-redefs
+ [metabot.settings/metabot-enabled? (constantly true)
+ metabot.settings/llm-metabot-configured? (constantly true)
+ usage/check-usage-limits! (constantly nil)
+ scope/resolve-user-permissions (constantly (assoc scope/all-yes-permissions
+ perm :no))]
(is (= :permission-denied (self/llm-call-unavailable-reason perm)))
(is (false? (self/llm-call-available? perm)))))
(testing "checks short-circuit in order: disabled before usage/permission"
- (with-redefs [metabot.settings/metabot-enabled? (constantly false)
- metabot.settings/llm-metabot-configured? (constantly false)
- usage/check-usage-limits! (constantly "limit")
- scope/resolve-user-permissions (constantly (assoc scope/all-yes-permissions
- perm :no))]
+ (mt/with-dynamic-fn-redefs
+ [metabot.settings/metabot-enabled? (constantly false)
+ metabot.settings/llm-metabot-configured? (constantly false)
+ usage/check-usage-limits! (constantly "limit")
+ scope/resolve-user-permissions (constantly (assoc scope/all-yes-permissions
+ perm :no))]
(is (= :metabot-disabled (self/llm-call-unavailable-reason perm)))))))
(deftest ^:parallel body-preview-test
diff --git a/test/metabase/metabot/tools/construct_numeric_permissions_test.clj b/test/metabase/metabot/tools/construct_numeric_permissions_test.clj
index fc7b10fc4e7..e7d1c0f229b 100644
--- a/test/metabase/metabot/tools/construct_numeric_permissions_test.clj
+++ b/test/metabase/metabot/tools/construct_numeric_permissions_test.clj
@@ -214,10 +214,10 @@
(mt/with-temp [:model/Database other {:engine :h2 :name "OtherDB-qcheck-test"}
:model/Table other-tbl {:db_id (:id other) :name "OTHER_TBL" :active true}]
(let [checked (atom [])
- orig api/query-check]
- (with-redefs [api/query-check (fn [& args]
- (swap! checked conj (vec args))
- (apply orig args))]
+ orig (mt/original-fn #'api/query-check)]
+ (mt/with-dynamic-fn-redefs [api/query-check (fn [& args]
+ (swap! checked conj (vec args))
+ (apply orig args))]
(attempt-as-rasta
{:lib/type "mbql/query"
:database (db-name)
@@ -427,7 +427,7 @@
(throw (ex-info "You don't have permissions to do that."
{:status-code 403}))
{:model entity :id id})))]
- (with-redefs [api/query-check deny-query-check]
+ (mt/with-dynamic-fn-redefs [api/query-check deny-query-check]
(let [forbidden (attempt-as-rasta
{:lib/type "mbql/query"
:database (db-name)
@@ -463,7 +463,7 @@
([obj] obj)
([entity id] (rec entity id nil))
([entity id & _] (swap! checked conj [entity id]) {:model entity :id id}))]
- (with-redefs [api/query-check record]
+ (mt/with-dynamic-fn-redefs [api/query-check record]
(attempt-as-rasta
{:lib/type "mbql/query"
:database (db-name)
diff --git a/test/metabase/metabot/tools/construct_representations_test.clj b/test/metabase/metabot/tools/construct_representations_test.clj
index 3a9d749116f..c147d546c04 100644
--- a/test/metabase/metabot/tools/construct_representations_test.clj
+++ b/test/metabase/metabot/tools/construct_representations_test.clj
@@ -24,7 +24,8 @@
[metabase.metabot.tools.recovery-hints :as v1-hints]
[metabase.models.interface :as mi]
[metabase.models.serialization.resolve :as serdes.resolve]
- [metabase.models.serialization.resolve.mp :as resolve.mp]))
+ [metabase.models.serialization.resolve.mp :as resolve.mp]
+ [metabase.test :as mt]))
(set! *warn-on-reflection* true)
@@ -1246,8 +1247,8 @@
`source-card` branch resolves the database id straight off the card row, before any
metadata provider or resolver exists."
[read-check f]
- (with-redefs [metabot.db/card (fn [id] (when (= id 500) {:id 500 :database_id 1}))
- api/read-check read-check]
+ (mt/with-dynamic-fn-redefs [metabot.db/card (fn [id] (when (= id 500) {:id 500 :database_id 1}))
+ api/read-check read-check]
(f)))
(deftest numeric-source-card-resolves-database-id-test
@@ -1323,7 +1324,7 @@
"distinct from the portable form's `:unknown-table` — the two want different\n"
"recovery vocabulary, so the keys must not be collapsed.")
(with-v2-surface
- (with-redefs [metabot.db/readable-active-table-database-id (fn [_] nil)]
+ (mt/with-dynamic-fn-redefs [metabot.db/readable-active-table-database-id (fn [_] nil)]
(try
(construct/resolve-database-id-from-first-stage
{"lib/type" "mbql/query"
@@ -1677,10 +1678,11 @@
(testing "repair's source-card lookups are best-effort and the query is resolved for real afterwards,
so a refusal in there must not be audited as an access attempt"
(let [seen (atom ::never-called)
- repair repr.repair/repair]
- (with-redefs [repr.repair/repair (fn [& args]
- (reset! seen resolve.mp/*audit-refusals?*)
- (apply repair args))]
+ repair (mt/original-fn #'repr.repair/repair)]
+ (mt/with-dynamic-fn-redefs
+ [repr.repair/repair (fn [& args]
+ (reset! seen resolve.mp/*audit-refusals?*)
+ (apply repair args))]
(with-mp-and-stubs!
(fn []
(construct/execute-representations-query
diff --git a/test/metabase/metabot/tools/entity_details_test.clj b/test/metabase/metabot/tools/entity_details_test.clj
index e13edec554d..9a76996acc3 100644
--- a/test/metabase/metabot/tools/entity_details_test.clj
+++ b/test/metabase/metabot/tools/entity_details_test.clj
@@ -408,10 +408,11 @@
(is (= raw-values
(#'entity-details/get-field-values {field-id {:values raw-values}} field-id))))
(testing "cache misses return the same raw-value shape"
- (with-redefs [params.field-values/current-user-can-fetch-field-values? (constantly true)
- params.field-values/get-or-create-field-values! (constantly {:values raw-values})
- params.field-values/get-or-create-field-values-for-current-user!
- (constantly {:values (mapv vector raw-values)})]
+ (mt/with-dynamic-fn-redefs
+ [params.field-values/current-user-can-fetch-field-values? (constantly true)
+ params.field-values/get-or-create-field-values! (constantly {:values raw-values})
+ params.field-values/get-or-create-field-values-for-current-user!
+ (constantly {:values (mapv vector raw-values)})]
(is (= raw-values
(#'entity-details/get-field-values {} field-id)))))))
@@ -457,9 +458,10 @@
:type :metric}]
(mt/with-no-data-perms-for-all-users!
(mt/with-current-user (mt/user->id :rasta)
- (with-redefs [params.field-values/field-id->field-values-for-current-user
- (fn [_]
- (throw (ex-info "field values must not be fetched" {})))]
+ (mt/with-dynamic-fn-redefs
+ [params.field-values/field-id->field-values-for-current-user
+ (fn [_]
+ (throw (ex-info "field values must not be fetched" {})))]
(let [output (:structured-output
(entity-details/get-metric-details {:metric-id metric-id
:with-segments? true}))]
diff --git a/test/metabase/metabot/tools/slackbot_query_test.clj b/test/metabase/metabot/tools/slackbot_query_test.clj
index 3fc5bf0c9b4..b9ee907efae 100644
--- a/test/metabase/metabot/tools/slackbot_query_test.clj
+++ b/test/metabase/metabot/tools/slackbot_query_test.clj
@@ -85,12 +85,13 @@
;; adhoc_viz data part, instructions text, error passthrough).
(defn- with-repr-stub! [stub-fn f]
- (with-redefs [construct/execute-representations-query stub-fn
- ;; `streaming/query->question-url` inspects the query; stub it too so the
- ;; fake query doesn't have to satisfy the real function's expectations.
- streaming/query->question-url
- (fn [_q display]
- (str "/question#fake" (when display (str "?d=" display))))]
+ (mt/with-dynamic-fn-redefs
+ [construct/execute-representations-query stub-fn
+ ;; `streaming/query->question-url` inspects the query; stub it too so the
+ ;; fake query doesn't have to satisfy the real function's expectations.
+ streaming/query->question-url
+ (fn [_q display]
+ (str "/question#fake" (when display (str "?d=" display))))]
(f)))
(deftest slackbot-tool-happy-path-test
diff --git a/test/metabase/model_persistence/task/persist_refresh_test.clj b/test/metabase/model_persistence/task/persist_refresh_test.clj
index ad9ade182ad..340d06daeb3 100644
--- a/test/metabase/model_persistence/task/persist_refresh_test.clj
+++ b/test/metabase/model_persistence/task/persist_refresh_test.clj
@@ -304,7 +304,7 @@
(is (true? @email-sent)))))))
(deftest persisted-model-refresh-error-event-accepts-quartz-trigger-test
- (with-redefs [messages/send-persistent-model-error-email! (fn [& _] nil)]
+ (mt/with-dynamic-fn-redefs [messages/send-persistent-model-error-email! (fn [& _] nil)]
(let [^org.quartz.Trigger trigger (#'task.persist-refresh/database-trigger {:id 1} "0 0 0/8 * * ? *")]
(is (identical?
trigger
diff --git a/test/metabase/mq/queue/on_error_test.clj b/test/metabase/mq/queue/on_error_test.clj
index 1f435a4e95c..cce0b08b2ba 100644
--- a/test/metabase/mq/queue/on_error_test.clj
+++ b/test/metabase/mq/queue/on_error_test.clj
@@ -181,6 +181,8 @@
attempts (atom 0)
orig analytics/inc!]
;; a metrics backend that is down exactly when we try to record the drop
+ ;; the drop path runs on an mq delivery worker thread, which doesn't inherit *local-redefs*
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [analytics/inc! (fn [metric & args]
(if (= metric :metabase-mq/batches-dropped)
(throw (ex-info "metrics backend is down" {}))
diff --git a/test/metabase/notification/send_test.clj b/test/metabase/notification/send_test.clj
index e1c7e46cecc..5bbb2402308 100644
--- a/test/metabase/notification/send_test.clj
+++ b/test/metabase/notification/send_test.clj
@@ -227,7 +227,7 @@
(testing "send email succeeds w/o retry"
(let [[hook state] (rt/retry-analytics-config-hook)]
(binding [retry/*test-time-config-hook* hook]
- (with-redefs [email/send-email! mt/fake-inbox-email-fn]
+ (mt/with-dynamic-fn-redefs [email/send-email! mt/fake-inbox-email-fn]
(mt/with-temporary-setting-values [email-smtp-host "fake_smtp_host"
email-smtp-port 587]
(mt/reset-inbox!)
@@ -249,7 +249,7 @@
(testing "send email fails b/c retry limit"
(let [[hook state] (rt/retry-analytics-config-hook {:max-retries 1})]
(binding [retry/*test-time-config-hook* hook]
- (with-redefs [email/send-email! (tu/works-after 2 mt/fake-inbox-email-fn)]
+ (mt/with-dynamic-fn-redefs [email/send-email! (tu/works-after 2 mt/fake-inbox-email-fn)]
(mt/with-temporary-setting-values [email-smtp-host "fake_smtp_host"
email-smtp-port 587]
(mt/reset-inbox!)
@@ -259,7 +259,7 @@
(testing "send email succeeds w/ retry"
(let [[hook state] (rt/retry-analytics-config-hook {:max-retries 1})]
(binding [retry/*test-time-config-hook* hook]
- (with-redefs [email/send-email! (tu/works-after 1 mt/fake-inbox-email-fn)]
+ (mt/with-dynamic-fn-redefs [email/send-email! (tu/works-after 1 mt/fake-inbox-email-fn)]
(mt/with-temporary-setting-values [email-smtp-host "fake_smtp_host"
email-smtp-port 587]
(mt/reset-inbox!)
@@ -290,13 +290,13 @@
(testing "post slack message fails b/c retry limit"
(let [[hook state] (rt/retry-analytics-config-hook {:max-retries 1})]
(binding [retry/*test-time-config-hook* hook]
- (with-redefs [slack/post-chat-message! (tu/works-after 2 (constantly nil))]
+ (mt/with-dynamic-fn-redefs [slack/post-chat-message! (tu/works-after 2 (constantly nil))]
(#'notification.send/channel-send-retrying! 1 :notification/card {:channel_type :channel/slack} fake-slack-notification)
(is (= {:success false, :retries 1} @state))))))
(testing "post slack message succeeds with retry"
(let [[hook state] (rt/retry-analytics-config-hook {:max-retries 1})]
(binding [retry/*test-time-config-hook* hook]
- (with-redefs [slack/post-chat-message! (tu/works-after 1 (constantly nil))]
+ (mt/with-dynamic-fn-redefs [slack/post-chat-message! (tu/works-after 1 (constantly nil))]
(#'notification.send/channel-send-retrying! 1 :notification/card {:channel_type :channel/slack} fake-slack-notification)
(is (= {:success true, :retries 1} @state))))))
(testing "post slack message to missing channel fails without retry"
diff --git a/test/metabase/premium_features/token_check_test.clj b/test/metabase/premium_features/token_check_test.clj
index a5d4dba36ce..3e793b2d6a1 100644
--- a/test/metabase/premium_features/token_check_test.clj
+++ b/test/metabase/premium_features/token_check_test.clj
@@ -732,10 +732,10 @@
{:soft-ttl (t/minutes 1) :hard-ttl (t/minutes 2)})
token (tu/random-token)
bomb (fn [& _] (throw (ex-info "DB should not be touched" {})))]
- (with-redefs [mdb/db-is-set-up? (constantly false)
- token-check/read-cache-from-db bomb
- token-check/write-cache-to-db! bomb
- token-check/clear-db-cache! bomb]
+ (mt/with-dynamic-fn-redefs [mdb/db-is-set-up? (constantly false)
+ token-check/read-cache-from-db bomb
+ token-check/write-cache-to-db! bomb
+ token-check/clear-db-cache! bomb]
(is (= good-response (token-check/-check-token checker token)))
(is (= 1 @call-count) "inner checker was called exactly once")
;; clear-cache! should also skip DB without error
diff --git a/test/metabase/pulse/dashboard_subscription_test.clj b/test/metabase/pulse/dashboard_subscription_test.clj
index aa9734008d4..55203a70c26 100644
--- a/test/metabase/pulse/dashboard_subscription_test.clj
+++ b/test/metabase/pulse/dashboard_subscription_test.clj
@@ -327,6 +327,9 @@
: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)]
(thunk)))
@@ -582,7 +585,7 @@
:fixture
(fn [_ thunk]
- (with-redefs [shared.params/value-string (fn [& _] (throw (ex-info "boom" {})))]
+ (mt/with-dynamic-fn-redefs [shared.params/value-string (fn [& _] (throw (ex-info "boom" {})))]
(thunk)))
:assert
@@ -1238,7 +1241,7 @@
:model/PulseChannel {pc-id :id} {:pulse_id pulse-id}
:model/PulseChannelRecipient _ {:user_id (pulse.test-util/rasta-id)
:pulse_channel_id pc-id}]
- (with-redefs [email.result-attachment/result-attachment result-attachment!]
+ (mt/with-dynamic-fn-redefs [email.result-attachment/result-attachment result-attachment!]
(pulse.send/send-pulse! pulse)
(is (= 1
(-> @mt/inbox
diff --git a/test/metabase/pulse/send_test.clj b/test/metabase/pulse/send_test.clj
index 139f2a5ed25..cbdf3e008c5 100644
--- a/test/metabase/pulse/send_test.clj
+++ b/test/metabase/pulse/send_test.clj
@@ -245,6 +245,9 @@
: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)]
(thunk)))
diff --git a/test/metabase/queries/models/card_test.clj b/test/metabase/queries/models/card_test.clj
index 12afa0cd172..eb67bc391f9 100644
--- a/test/metabase/queries/models/card_test.clj
+++ b/test/metabase/queries/models/card_test.clj
@@ -1296,7 +1296,7 @@
(deftest assert-no-source-card-id-for-native-query-test
(testing "assertion fires if native query has source_card_id set"
- (with-redefs [card/populate-query-fields identity]
+ (mt/with-dynamic-fn-redefs [card/populate-query-fields identity]
(is (thrown-with-msg? Exception #"Assert failed"
(t2/insert! :model/Card
{:name "Bad Card"
diff --git a/test/metabase/sample_data/impl_test.clj b/test/metabase/sample_data/impl_test.clj
index fb29d93b187..f7d8f2ae649 100644
--- a/test/metabase/sample_data/impl_test.clj
+++ b/test/metabase/sample_data/impl_test.clj
@@ -284,7 +284,7 @@
(perms/set-database-permission! (perms/all-users-group) (:id old-sample) :perms/create-queries :no)
(perms/set-database-permission! custom-group (:id old-sample) :perms/create-queries :query-builder)
(let [expected-perms (db-level-perms (:id old-sample))]
- (with-redefs [config/load-sample-content? (constantly true)]
+ (mt/with-dynamic-fn-redefs [config/load-sample-content? (constantly true)]
(#'sample-data/update-sample-database-if-needed! old-sample))
(let [new-sample (t2/select-one :model/Database :is_sample true :engine :sqlite)]
(is (some? new-sample) "the swap created a SQLite sample database")
diff --git a/test/metabase/search/ingestion_test.clj b/test/metabase/search/ingestion_test.clj
index e5c5d00af06..c012de5e661 100644
--- a/test/metabase/search/ingestion_test.clj
+++ b/test/metabase/search/ingestion_test.clj
@@ -33,7 +33,7 @@
:name "Test Name"
:description "Test Description"
:other-field "Other Value"}]
- (with-redefs [search.spec/spec spec-fn]
+ (mt/with-dynamic-fn-redefs [search.spec/spec spec-fn]
(is (= "Test Name Test Description"
(#'search.ingestion/searchable-text record))))))
(testing "searchable-text with map format and transforms"
@@ -42,7 +42,7 @@
record {:model "test"
:name "CamelCaseTest"
:description "Simple description"}]
- (with-redefs [search.spec/spec spec-fn]
+ (mt/with-dynamic-fn-redefs [search.spec/spec spec-fn]
(is (= "CamelCaseTest Camel Case Test Simple description"
(#'search.ingestion/searchable-text record))))))
(testing "searchable-text filters out blank values"
@@ -51,7 +51,7 @@
:name "Test Name"
:description " " ;; whitespace only
:empty-field nil}]
- (with-redefs [search.spec/spec spec-fn]
+ (mt/with-dynamic-fn-redefs [search.spec/spec spec-fn]
(is (= "Test Name"
(#'search.ingestion/searchable-text record)))))))
@@ -62,7 +62,7 @@
:name "Sales Dashboard"
:description "Shows quarterly sales data"
:other-field "Other Value"}]
- (with-redefs [search.spec/spec spec-fn]
+ (mt/with-dynamic-fn-redefs [search.spec/spec spec-fn]
(is (= "[card]\nname: Sales Dashboard\ndescription: Shows quarterly sales data"
(#'search.ingestion/embeddable-text record))))))
(testing "embeddable-text with map format"
@@ -71,7 +71,7 @@
record {:model "dashboard"
:name "Test Dashboard"
:description "A test dashboard"}]
- (with-redefs [search.spec/spec spec-fn]
+ (mt/with-dynamic-fn-redefs [search.spec/spec spec-fn]
(is (= "[dashboard]\nname: Test Dashboard\ndescription: A test dashboard"
(#'search.ingestion/embeddable-text record))))))
(testing "embeddable-text filters out blank values"
@@ -80,14 +80,14 @@
:name "Test Card"
:description " "
:empty-field nil}]
- (with-redefs [search.spec/spec spec-fn]
+ (mt/with-dynamic-fn-redefs [search.spec/spec spec-fn]
(is (= "[card]\nname: Test Card"
(#'search.ingestion/embeddable-text record))))))
(testing "embeddable-text does not apply transform functions"
(let [spec-fn (constantly {:search-terms {:name search.spec/explode-camel-case}})
record {:model "table"
:name "CamelCaseTest"}]
- (with-redefs [search.spec/spec spec-fn]
+ (mt/with-dynamic-fn-redefs [search.spec/spec spec-fn]
(is (= "[table]\nname: CamelCaseTest"
(#'search.ingestion/embeddable-text record))
"Transformation functions should not be applied to embeddable text for semantic search"))))
@@ -97,7 +97,7 @@
record {:model "document"
:name "Q3 Planning"
:document "the full document body"}]
- (with-redefs [search.spec/spec spec-fn]
+ (mt/with-dynamic-fn-redefs [search.spec/spec spec-fn]
(is (= "[document]\nname: Q3 Planning"
(#'search.ingestion/embeddable-text record))
"Excluded fields must not appear in the semantic-search embedding text")
@@ -203,10 +203,12 @@
(deftest bulk-ingest!-caches-metadata-providers-test
(testing "bulk-ingest! caches metadata providers so the factory is only called once per database-id"
(let [factory-calls (atom 0)]
- (with-redefs [search.engine/active-engines (fn []
- (simulate-metadata-lookups)
- nil)
- metadata.jvm/application-database-metadata-provider-factory (counting-factory factory-calls)]
+ (mt/with-dynamic-fn-redefs
+ [search.engine/active-engines
+ (fn []
+ (simulate-metadata-lookups)
+ nil)
+ metadata.jvm/application-database-metadata-provider-factory (counting-factory factory-calls)]
(search.ingestion/bulk-ingest! [])
(is (= 1 @factory-calls)
"Factory should be called once, not once per metadata-provider lookup")))))
@@ -215,10 +217,12 @@
(testing "bulk-ingest! reuses an outer cache and does not rebuild providers already in it"
(let [factory-calls (atom 0)
existing-cache (atom (cache/basic-cache-factory {}))]
- (with-redefs [search.engine/active-engines (fn []
- (simulate-metadata-lookups)
- nil)
- metadata.jvm/application-database-metadata-provider-factory (counting-factory factory-calls)]
+ (mt/with-dynamic-fn-redefs
+ [search.engine/active-engines
+ (fn []
+ (simulate-metadata-lookups)
+ nil)
+ metadata.jvm/application-database-metadata-provider-factory (counting-factory factory-calls)]
(binding [metadata.jvm/*metadata-provider-cache* existing-cache]
(metadata.jvm/application-database-metadata-provider 1)
(let [pre-calls @factory-calls]
diff --git a/test/metabase/server/middleware/log_test.clj b/test/metabase/server/middleware/log_test.clj
index d5714c439e6..314eab1ddd4 100644
--- a/test/metabase/server/middleware/log_test.clj
+++ b/test/metabase/server/middleware/log_test.clj
@@ -40,8 +40,8 @@
(fn [_request respond _raise]
(respond (with-meta {:status 200 :body "ok"}
{:metabase-user-id 42}))))]
- (with-redefs [mw.log/log-info (fn [info]
- (deliver logged-user-id (get-in info [:log-context :metabase-user-id])))]
+ (mt/with-dynamic-fn-redefs [mw.log/log-info (fn [info]
+ (deliver logged-user-id (get-in info [:log-context :metabase-user-id])))]
(handler {:request-method :post :uri "/api/session"}
identity
identity)
diff --git a/test/metabase/server/middleware/security_test.clj b/test/metabase/server/middleware/security_test.clj
index ba9081dfd23..7a90b6e6679 100644
--- a/test/metabase/server/middleware/security_test.clj
+++ b/test/metabase/server/middleware/security_test.clj
@@ -178,16 +178,16 @@
(deftest data-app-form-action-test
(testing "form-action is ALWAYS set on a data-app iframe document (its absence = admin provisioning)"
(doseq [hosts [[] ["https://api.example.com"]]]
- (with-redefs [mw.security/data-app-connect-src-hosts (constantly hosts)]
+ (mt/with-dynamic-fn-redefs [mw.security/data-app-connect-src-hosts (constantly hosts)]
(is (some? (csp-directive-for "/embed/apps/sales" "form-action"))))))
(testing "with no allowed_hosts, native <form action> submits are blocked (client-side onSubmit still works)"
- (with-redefs [mw.security/data-app-connect-src-hosts (constantly [])]
+ (mt/with-dynamic-fn-redefs [mw.security/data-app-connect-src-hosts (constantly [])]
(is (= "form-action 'none'" (csp-directive-for "/embed/apps/sales" "form-action")))
(is (= "form-action 'none'"
(csp-directive-for "/embed/apps/sales/sub/route" "form-action")))))
(testing "form-action mirrors the app's allowed_hosts (like connect-src)"
- (with-redefs [mw.security/data-app-connect-src-hosts
- (constantly ["https://api.example.com" "https://*.trusted.test"])]
+ (mt/with-dynamic-fn-redefs [mw.security/data-app-connect-src-hosts
+ (constantly ["https://api.example.com" "https://*.trusted.test"])]
(is (= "form-action https://api.example.com https://*.trusted.test"
(csp-directive-for "/embed/apps/sales" "form-action")))))
(testing "other documents leave form-action unset (falls through to no restriction)"
@@ -214,7 +214,7 @@
;; A global iframe host (wikipedia) is configured but must NOT leak into a data
;; app's frame-src — the app can only frame what it declares.
(mt/with-temporary-setting-values [allowed-iframe-hosts "https://www.wikipedia.org"]
- (with-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://example.com"])]
+ (mt/with-dynamic-fn-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://example.com"])]
;; Both the top page and the iframe doc: the top page's `frame-src` gates
;; what the iframe below it may navigate to.
(doseq [uri ["/apps/sales" "/embed/apps/sales"]]
@@ -224,11 +224,11 @@
(is (not (str/includes? frame-src "wikipedia"))
(str uri " must not include the instance-wide iframe hosts")))))))
(testing "with no allowed_hosts, a data app can only frame 'self'"
- (with-redefs [mw.security/data-app-connect-src-hosts (constantly [])]
+ (mt/with-dynamic-fn-redefs [mw.security/data-app-connect-src-hosts (constantly [])]
(is (= "frame-src 'self'" (csp-directive-for "/embed/apps/sales" "frame-src")))))
(testing "non-data-app documents keep the instance-wide iframe hosts, not app hosts"
(mt/with-temporary-setting-values [allowed-iframe-hosts "https://www.wikipedia.org"]
- (with-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://example.com"])]
+ (mt/with-dynamic-fn-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://example.com"])]
(let [frame-src (csp-directive-for "/embed/dashboard/abc" "frame-src")]
(is (str/includes? frame-src "wikipedia"))
(is (not (str/includes? frame-src "https://example.com"))))))))
@@ -236,7 +236,7 @@
(deftest data-app-hosts-only-for-signed-in-users-test
(testing "a signed-out request never sees an app's allowed_hosts in its CSP, and never triggers the lookup"
(let [lookups (atom 0)]
- (with-redefs [mw.security/data-app-connect-src-hosts (fn [_slug] (swap! lookups inc) ["https://example.com"])]
+ (mt/with-dynamic-fn-redefs [mw.security/data-app-connect-src-hosts (fn [_slug] (swap! lookups inc) ["https://example.com"])]
(doseq [uri ["/embed/apps/sales" "/embed/apps/sales/sub/route" "/apps/sales"]]
(let [csp (get (headers-for-request {:uri uri}) "Content-Security-Policy")]
(is (not (str/includes? csp "https://example.com")) uri)))
@@ -247,7 +247,7 @@
(is (zero? @lookups)))))
(testing "a signed-out request keeps the data-app policy with an empty allowlist rather than the instance-wide one"
(mt/with-temporary-setting-values [allowed-iframe-hosts "https://widgets.example"]
- (with-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://example.com"])]
+ (mt/with-dynamic-fn-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://example.com"])]
(doseq [uri ["/embed/apps/sales" "/apps/sales"]]
(is (= "frame-src 'self'"
(-> (headers-for-request {:uri uri})
@@ -255,7 +255,7 @@
(header->directive "frame-src")))
uri)))))
(testing "a signed-in request gets them"
- (with-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://example.com"])]
+ (mt/with-dynamic-fn-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://example.com"])]
(doseq [uri ["/embed/apps/sales" "/apps/sales"]]
(is (str/includes? (get (headers-for-request {:uri uri :metabase-user-id 1}) "Content-Security-Policy")
"https://example.com")
@@ -264,8 +264,8 @@
(deftest data-app-instance-origin-excluded-test
(testing "the Metabase instance origin is dropped from a data app's allowlist even if listed"
(mt/with-temporary-setting-values [site-url "https://mymetabase.example"]
- (with-redefs [mw.security/data-app-connect-src-hosts
- (constantly ["https://mymetabase.example" "https://api.allowed.test"])]
+ (mt/with-dynamic-fn-redefs [mw.security/data-app-connect-src-hosts
+ (constantly ["https://mymetabase.example" "https://api.allowed.test"])]
(let [form-action (csp-directive-for "/embed/apps/sales" "form-action")
frame-src (csp-directive-for "/embed/apps/sales" "frame-src")
connect-src (csp-directive-for "/embed/apps/sales" "connect-src")]
@@ -284,10 +284,10 @@
;; place, `form-action https://*.company.com` matches `mb.company.com`, letting a
;; hostile bundle native-submit a `<form action="…/api/user">` and provision an admin.
(mt/with-temporary-setting-values [site-url "https://mb.company.com"]
- (with-redefs [mw.security/data-app-connect-src-hosts
- (constantly ["https://*.company.com" ; covers mb.company.com -> must be dropped
- "https://*.othercdn.com" ; unrelated wildcard -> must survive
- "https://api.allowed.test"])]
+ (mt/with-dynamic-fn-redefs [mw.security/data-app-connect-src-hosts
+ (constantly ["https://*.company.com" ; covers mb.company.com -> must be dropped
+ "https://*.othercdn.com" ; unrelated wildcard -> must survive
+ "https://api.allowed.test"])]
(let [form-action (csp-directive-for "/embed/apps/sales" "form-action")
frame-src (csp-directive-for "/embed/apps/sales" "frame-src")
connect-src (csp-directive-for "/embed/apps/sales" "connect-src")]
@@ -315,9 +315,9 @@
;; entry the bundle spells with the default port or different case must be dropped too.
(testing "the instance origin spelled with its default port is dropped when site-url is portless"
(mt/with-temporary-setting-values [site-url "https://mb.company.com"]
- (with-redefs [mw.security/data-app-connect-src-hosts
- (constantly ["https://mb.company.com:443" ; the instance, default port -> must be dropped
- "https://api.allowed.test"])] ; unrelated external host -> must survive
+ (mt/with-dynamic-fn-redefs [mw.security/data-app-connect-src-hosts
+ (constantly ["https://mb.company.com:443" ; the instance, default port -> must be dropped
+ "https://api.allowed.test"])] ; unrelated external host -> must survive
(let [form-action (csp-directive-for "/embed/apps/sales" "form-action")
frame-src (csp-directive-for "/embed/apps/sales" "frame-src")
connect-src (csp-directive-for "/embed/apps/sales" "connect-src")]
@@ -330,9 +330,9 @@
(str directive " must keep an external host")))))))
(testing "the instance origin in a different host case is dropped (DNS/CSP host matching is case-insensitive)"
(mt/with-temporary-setting-values [site-url "https://MB.Company.COM"]
- (with-redefs [mw.security/data-app-connect-src-hosts
- (constantly ["https://mb.company.com" ; the instance, lower-cased -> must be dropped
- "https://api.allowed.test"])] ; unrelated external host -> must survive
+ (mt/with-dynamic-fn-redefs [mw.security/data-app-connect-src-hosts
+ (constantly ["https://mb.company.com" ; the instance, lower-cased -> must be dropped
+ "https://api.allowed.test"])] ; unrelated external host -> must survive
(let [form-action (csp-directive-for "/embed/apps/sales" "form-action")
frame-src (csp-directive-for "/embed/apps/sales" "frame-src")
connect-src (csp-directive-for "/embed/apps/sales" "connect-src")]
@@ -352,9 +352,9 @@
;; re-opens the admin-provisioning submit the barrier exists to block.
(testing "an http entry covering an https instance is dropped (CSP http→https upgrade)"
(mt/with-temporary-setting-values [site-url "https://mb.company.com"]
- (with-redefs [mw.security/data-app-connect-src-hosts
- (constantly ["http://mb.company.com" ; the instance over http -> must be dropped
- "https://api.allowed.test"])] ; unrelated external host -> must survive
+ (mt/with-dynamic-fn-redefs [mw.security/data-app-connect-src-hosts
+ (constantly ["http://mb.company.com" ; the instance over http -> must be dropped
+ "https://api.allowed.test"])] ; unrelated external host -> must survive
(let [form-action (csp-directive-for "/embed/apps/sales" "form-action")
frame-src (csp-directive-for "/embed/apps/sales" "frame-src")
connect-src (csp-directive-for "/embed/apps/sales" "connect-src")]
@@ -367,30 +367,30 @@
(str directive " must keep an external host")))))))
(testing "the reverse (https entry, http instance) is left in place — the browser has no https→http upgrade"
(mt/with-temporary-setting-values [site-url "http://mb.company.com"]
- (with-redefs [mw.security/data-app-connect-src-hosts
- (constantly ["https://mb.company.com"])]
+ (mt/with-dynamic-fn-redefs [mw.security/data-app-connect-src-hosts
+ (constantly ["https://mb.company.com"])]
(is (str/includes? (csp-directive-for "/embed/apps/sales" "form-action")
"https://mb.company.com")
"an https entry does not cover an http instance, so it must not be over-dropped")))))
(deftest data-app-connect-src-test
(testing "a data app's allowed_hosts are added to the iframe document's connect-src"
- (with-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://api.example.com"])]
+ (mt/with-dynamic-fn-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://api.example.com"])]
(is (str/includes? (csp-directive-for "/embed/apps/sales" "connect-src")
"https://api.example.com"))))
(testing "with no allowed_hosts, the iframe connect-src has no app hosts (same as any doc)"
- (with-redefs [mw.security/data-app-connect-src-hosts (constantly [])]
+ (mt/with-dynamic-fn-redefs [mw.security/data-app-connect-src-hosts (constantly [])]
(is (= (csp-directive-for "/embed/apps/sales" "connect-src")
(csp-directive-for "/embed/dashboard/abc" "connect-src")))))
(testing "the top-level /data-app page keeps a tight connect-src — hosts go to the iframe doc, not here"
- (with-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://api.example.com"])]
+ (mt/with-dynamic-fn-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://api.example.com"])]
(is (not (str/includes? (csp-directive-for "/apps/sales" "connect-src")
"https://api.example.com")))
;; ...but the top page still gets them in frame-src (it gates the iframe's nav).
(is (str/includes? (csp-directive-for "/apps/sales" "frame-src")
"https://api.example.com"))))
(testing "non-data-app documents don't get app hosts in connect-src"
- (with-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://api.example.com"])]
+ (mt/with-dynamic-fn-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://api.example.com"])]
(is (not (str/includes? (csp-directive-for "/embed/dashboard/abc" "connect-src")
"https://api.example.com"))))))
@@ -498,7 +498,7 @@
(is (str/includes? (csp-directive-for "/embed/apps/sales" "img-src")
"https://cdn.example.com"))))
(testing "and the app's own allowed_hosts (mirroring connect-src/frame-src), plus 'self'"
- (with-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://api.myapp.com"])]
+ (mt/with-dynamic-fn-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://api.myapp.com"])]
(let [img-src (csp-directive-for "/embed/apps/sales" "img-src")]
(is (str/includes? img-src "https://api.myapp.com"))
(is (str/includes? img-src "'self'")))))))
diff --git a/test/metabase/server/middleware/session_oauth_test.clj b/test/metabase/server/middleware/session_oauth_test.clj
index c67fd240109..c7f2f2eb080 100644
--- a/test/metabase/server/middleware/session_oauth_test.clj
+++ b/test/metabase/server/middleware/session_oauth_test.clj
@@ -191,9 +191,9 @@
(deftest bearer-bridge-precedence-test
(testing "session/api-key auth takes precedence — bearer resolution is not even attempted"
(let [called? (atom false)]
- (with-redefs [oauth-server/resolve-access-token (fn [_] (reset! called? true) nil)
- ;; pretend an API key authenticated the request
- mw.session/current-user-info-for-api-key (fn [_] {:metabase-user-id 99 :is-superuser? false})]
+ (mt/with-dynamic-fn-redefs [oauth-server/resolve-access-token (fn [_] (reset! called? true) nil)
+ ;; pretend an API key authenticated the request
+ mw.session/current-user-info-for-api-key (fn [_] {:metabase-user-id 99 :is-superuser? false})]
(let [req (merge-current-user-info {:headers {"authorization" "Bearer anything"
"x-api-key" "mb_whatever"}})]
(is (= 99 (:metabase-user-id req)))
diff --git a/test/metabase/session/api_test.clj b/test/metabase/session/api_test.clj
index e3e29724b90..f55a5dc15f7 100644
--- a/test/metabase/session/api_test.clj
+++ b/test/metabase/session/api_test.clj
@@ -254,9 +254,9 @@
(deftest forgot-password-initiate-reset-test
(testing "POST /api/session/forgot_password - initiate password reset"
- (with-redefs [api.session/forgot-password-impl
- (let [orig @#'api.session/forgot-password-impl]
- (fn [& args] (u/deref-with-timeout (apply orig args) 1000)))]
+ (mt/with-dynamic-fn-redefs [api.session/forgot-password-impl
+ (let [orig (mt/original-fn #'api.session/forgot-password-impl)]
+ (fn [& args] (u/deref-with-timeout (apply orig args) 1000)))]
(mt/with-fake-inbox
(letfn [(reset-fields-set? []
(boolean (t2/select-one :model/AuthIdentity :user_id (mt/user->id :rasta)
@@ -274,9 +274,9 @@
(deftest forgot-password-uses-site-url-test
(testing "POST /api/session/forgot_password - uses site-url in email"
- (with-redefs [api.session/forgot-password-impl
- (let [orig @#'api.session/forgot-password-impl]
- (fn [& args] (u/deref-with-timeout (apply orig args) 1000)))]
+ (mt/with-dynamic-fn-redefs [api.session/forgot-password-impl
+ (let [orig (mt/original-fn #'api.session/forgot-password-impl)]
+ (fn [& args] (u/deref-with-timeout (apply orig args) 1000)))]
(let [my-url "abcdefghij"]
(mt/with-temporary-setting-values [site-url my-url]
(mt/with-fake-inbox
@@ -305,9 +305,9 @@
(deftest forgot-password-google-sso-enabled-test
(testing "POST /api/session/forgot_password - Google SSO user cannot reset when Google SSO enabled"
- (with-redefs [api.session/forgot-password-impl
- (let [orig @#'api.session/forgot-password-impl]
- (fn [& args] (u/deref-with-timeout (apply orig args) 1000)))]
+ (mt/with-dynamic-fn-redefs [api.session/forgot-password-impl
+ (let [orig (mt/original-fn #'api.session/forgot-password-impl)]
+ (fn [& args] (u/deref-with-timeout (apply orig args) 1000)))]
(mt/with-temp [:model/User g-user {:first_name "g"
:last_name "user"
@@ -325,9 +325,9 @@
(deftest forgot-password-google-sso-disabled-test
(testing "POST /api/session/forgot_password - Google SSO user can reset when Google SSO disabled"
- (with-redefs [api.session/forgot-password-impl
- (let [orig @#'api.session/forgot-password-impl]
- (fn [& args] (u/deref-with-timeout (apply orig args) 1000)))]
+ (mt/with-dynamic-fn-redefs [api.session/forgot-password-impl
+ (let [orig (mt/original-fn #'api.session/forgot-password-impl)]
+ (fn [& args] (u/deref-with-timeout (apply orig args) 1000)))]
(mt/with-temp [:model/User g-user {:first_name "g"
:last_name "user"
@@ -348,10 +348,10 @@
(doseq [sso-source [:saml :jwt :oidc :slack :scim]]
(testing (str "sso_source = " sso-source)
;; Mock sso-source-enabled? to return false (provider is disabled, e.g., after downgrade)
- (with-redefs [api.session/forgot-password-impl
- (let [orig @#'api.session/forgot-password-impl]
- (fn [& args] (u/deref-with-timeout (apply orig args) 1000)))
- metabase.sso.settings/sso-source-enabled? (constantly false)]
+ (mt/with-dynamic-fn-redefs [api.session/forgot-password-impl
+ (let [orig (mt/original-fn #'api.session/forgot-password-impl)]
+ (fn [& args] (u/deref-with-timeout (apply orig args) 1000)))
+ metabase.sso.settings/sso-source-enabled? (constantly false)]
(mt/with-temp [:model/User sso-user {:first_name "sso"
:last_name "user"
:email (str (name sso-source) "[email protected]")
@@ -369,10 +369,10 @@
(doseq [sso-source [:saml :jwt :oidc :slack :scim]]
(testing (str "sso_source = " sso-source)
;; Mock sso-source-enabled? to return true (provider is active)
- (with-redefs [api.session/forgot-password-impl
- (let [orig @#'api.session/forgot-password-impl]
- (fn [& args] (u/deref-with-timeout (apply orig args) 1000)))
- metabase.sso.settings/sso-source-enabled? (fn [src] (= (keyword src) sso-source))]
+ (mt/with-dynamic-fn-redefs [api.session/forgot-password-impl
+ (let [orig (mt/original-fn #'api.session/forgot-password-impl)]
+ (fn [& args] (u/deref-with-timeout (apply orig args) 1000)))
+ metabase.sso.settings/sso-source-enabled? (fn [src] (= (keyword src) sso-source))]
(mt/with-temp [:model/User sso-user {:first_name "sso"
:last_name "user"
:email (str (name sso-source) "[email protected]")
@@ -387,9 +387,9 @@
(deftest forgot-password-event-test
(mt/with-premium-features #{:audit-app}
- (with-redefs [api.session/forgot-password-impl
- (let [orig @#'api.session/forgot-password-impl]
- (fn [& args] (u/deref-with-timeout (apply orig args) 1000)))]
+ (mt/with-dynamic-fn-redefs [api.session/forgot-password-impl
+ (let [orig (mt/original-fn #'api.session/forgot-password-impl)]
+ (fn [& args] (u/deref-with-timeout (apply orig args) 1000)))]
(mt/with-model-cleanup [:model/User]
(testing "Test that forgot password event is logged."
(mt/client :post 204 "session/forgot_password"
diff --git a/test/metabase/sql_parsing/core_test.clj b/test/metabase/sql_parsing/core_test.clj
index 54c36f9544c..eb0c18580cd 100644
--- a/test/metabase/sql_parsing/core_test.clj
+++ b/test/metabase/sql_parsing/core_test.clj
@@ -6,6 +6,7 @@
[metabase.analytics-interface.core :as analytics-interface]
[metabase.sql-parsing.core :as sql-parsing]
[metabase.sql-parsing.graal :as graal]
+ [metabase.test.util.dynamic-redefs :as dynamic-redefs]
[metabase.util :as u])
(:import
(java.util.concurrent TimeoutException)))
@@ -816,11 +817,11 @@
(testing (str "A fired Python-call timeout still surfaces as TimeoutException from the API even if "
"the timeout-metric bump throws — a misconfigured analytics registry must not shadow "
"the timeout (#77084).")
- (with-redefs [;; force the timeout branch of do-with-python-context without waiting 30s
- graal/with-timeout* (fn [_ _] :metabase.sql-parsing.graal/timeout)
- ;; poison only the timeout metric; leave the acquisition inc! alone
- analytics-interface/inc! (fn [k & _]
- (when (= k :metabase-sql-parsing/context-timeouts)
- (throw (Exception. "boom"))))]
+ (dynamic-redefs/with-dynamic-fn-redefs [;; force the timeout branch of do-with-python-context without waiting 30s
+ graal/with-timeout* (fn [_ _] :metabase.sql-parsing.graal/timeout)
+ ;; poison only the timeout metric; leave the acquisition inc! alone
+ analytics-interface/inc! (fn [k & _]
+ (when (= k :metabase-sql-parsing/context-timeouts)
+ (throw (Exception. "boom"))))]
(is (thrown? TimeoutException
(sql-parsing/referenced-tables "postgres" "SELECT 1"))))))
diff --git a/test/metabase/sync/events/sync_database_test.clj b/test/metabase/sync/events/sync_database_test.clj
index e4ba7c1cf41..a0105bac695 100644
--- a/test/metabase/sync/events/sync_database_test.clj
+++ b/test/metabase/sync/events/sync_database_test.clj
@@ -13,9 +13,9 @@
(testing "The :event/database-create handler kicks off a sync on a new thread by default"
(mt/with-temp [:model/Database {:as db} {:is_full_sync true}]
(let [calls (atom 0)]
- (with-redefs [quick-task/submit-task! (fn [task] (task))
- sync/sync-database! (fn [_] (swap! calls inc))
- sync-metadata/sync-db-metadata! (fn [_] (swap! calls inc))]
+ (mt/with-dynamic-fn-redefs [quick-task/submit-task! (fn [task] (task))
+ sync/sync-database! (fn [_] (swap! calls inc))
+ sync-metadata/sync-db-metadata! (fn [_] (swap! calls inc))]
(testing "default (disable-auto-sync=false): a sync entry point is invoked"
(reset! calls 0)
(events/publish-event! :event/database-create {:object db :user-id (mt/user->id :crowberto)})
diff --git a/test/metabase/sync/field_values_test.clj b/test/metabase/sync/field_values_test.clj
index 89319361df2..4ca54865153 100644
--- a/test/metabase/sync/field_values_test.clj
+++ b/test/metabase/sync/field_values_test.clj
@@ -368,18 +368,18 @@
:base_type :type/Text, :has_field_values :list}
:model/Field plain-c {:table_id tbl-id, :name "plain"
:base_type :type/Text, :has_field_values :list}]
- (with-redefs [sync.field-values/fetch-distinct-for-table
- (fn [_table fields]
- (swap! calls-to-fetch-distinct-for-table conj (set (map :id fields)))
- {:results (into {} (map (fn [f] [(:id f) {:values []}])) fields)
- :queries 1
- :failed-fields #{}})
- sync.field-values/fetch-distinct-per-field
- (fn [fields]
- (swap! calls-to-fetch-distinct-per-field conj (set (map :id fields)))
- {:results (into {} (map (fn [f] [(:id f) {:values []}])) fields)
- :queries (count fields)
- :failed-fields #{}})]
+ (mt/with-dynamic-fn-redefs [sync.field-values/fetch-distinct-for-table
+ (fn [_table fields]
+ (swap! calls-to-fetch-distinct-for-table conj (set (map :id fields)))
+ {:results (into {} (map (fn [f] [(:id f) {:values []}])) fields)
+ :queries 1
+ :failed-fields #{}})
+ sync.field-values/fetch-distinct-per-field
+ (fn [fields]
+ (swap! calls-to-fetch-distinct-per-field conj (set (map :id fields)))
+ {:results (into {} (map (fn [f] [(:id f) {:values []}])) fields)
+ :queries (count fields)
+ :failed-fields #{}})]
(#'sync.field-values/sync-fields-for-table! table [nested-a nested-b plain-c] {})
(testing "Plain field goes to batch path"
(is (= [#{(:id plain-c)}] @calls-to-fetch-distinct-for-table)))
diff --git a/test/metabase/sync/sync_metadata_test.clj b/test/metabase/sync/sync_metadata_test.clj
index 8a613c6cbd2..8cd778e0d1c 100644
--- a/test/metabase/sync/sync_metadata_test.clj
+++ b/test/metabase/sync/sync_metadata_test.clj
@@ -42,7 +42,7 @@
(testing "When fetching DB metadata throws (e.g. Athena lacking glue:GetDatabases, GHY-3534),"
(testing "the initial sync status is marked aborted instead of left stuck at \"incomplete\""
(mt/with-temp [:model/Database db {:initial_sync_status "incomplete"}]
- (with-redefs [fetch-metadata/db-metadata (fn [_] (throw (ex-info "boom" {})))]
+ (mt/with-dynamic-fn-redefs [fetch-metadata/db-metadata (fn [_] (throw (ex-info "boom" {})))]
(is (thrown? Throwable
(#'sync-metadata/sync-db-metadata!* db))))
(is (= "aborted"
@@ -54,11 +54,11 @@
(testing "the initial sync status is marked aborted instead of falsely reporting \"complete\""
(mt/with-temp-copy-of-db
(t2/update! :model/Database (mt/id) {:initial_sync_status "incomplete"})
- (with-redefs [fetch-metadata/fields-metadata
- (fn [& _]
- (throw (doto (java.sql.SQLSyntaxErrorException.
- "Unknown column 'generation_expression' in 'field list'")
- (.setStackTrace (into-array StackTraceElement [])))))]
+ (mt/with-dynamic-fn-redefs [fetch-metadata/fields-metadata
+ (fn [& _]
+ (throw (doto (java.sql.SQLSyntaxErrorException.
+ "Unknown column 'generation_expression' in 'field list'")
+ (.setStackTrace (into-array StackTraceElement [])))))]
(#'sync-metadata/sync-db-metadata!* (t2/select-one :model/Database :id (mt/id))))
(is (= "aborted"
(t2/select-one-fn :initial_sync_status :model/Database (mt/id)))))))))
diff --git a/test/metabase/sync/task/sync_databases_test.clj b/test/metabase/sync/task/sync_databases_test.clj
index b62b65c7d0e..84cc77785fb 100644
--- a/test/metabase/sync/task/sync_databases_test.clj
+++ b/test/metabase/sync/task/sync_databases_test.clj
@@ -179,7 +179,7 @@
(mt/with-temp [:model/Database {db-id :id} {:is_full_sync true}]
(testing "SyncAndAnalyzeDatabase: inner sync orchestrator is skipped when the flag is on"
(let [calls (atom 0)]
- (with-redefs [task.sync-databases/sync-and-analyze-database*! (fn [_] (swap! calls inc))]
+ (mt/with-dynamic-fn-redefs [task.sync-databases/sync-and-analyze-database*! (fn [_] (swap! calls inc))]
(testing "default (flag=false): job proceeds and calls the inner orchestrator"
(reset! calls 0)
(#'task.sync-databases/sync-and-analyze-database! (MockJobExecutionContext. {"db-id" db-id}))
@@ -191,7 +191,7 @@
(is (zero? @calls))))))
(testing "UpdateFieldValues: field-values update is skipped when the flag is on"
(let [calls (atom 0)]
- (with-redefs [sync.field-values/update-field-values! (fn [_] (swap! calls inc))]
+ (mt/with-dynamic-fn-redefs [sync.field-values/update-field-values! (fn [_] (swap! calls inc))]
(testing "default (flag=false): job proceeds and calls update-field-values!"
(reset! calls 0)
(#'task.sync-databases/update-field-values! (MockJobExecutionContext. {"db-id" db-id}))
@@ -207,7 +207,7 @@
(mt/with-temp [:model/Database {db-id :id} {:is_stub false}
:model/Database {stub-id :id} {:is_stub true}]
(let [calls (atom 0)]
- (with-redefs [task.sync-databases/sync-and-analyze-database*! (fn [_] (swap! calls inc))]
+ (mt/with-dynamic-fn-redefs [task.sync-databases/sync-and-analyze-database*! (fn [_] (swap! calls inc))]
(testing "non-stub: inner orchestrator is called"
(reset! calls 0)
(#'task.sync-databases/sync-and-analyze-database! (MockJobExecutionContext. {"db-id" db-id}))
@@ -222,7 +222,7 @@
(mt/with-temp [:model/Database non-stub {:is_stub false}
:model/Database stub {:is_stub true}]
(let [calls (atom 0)]
- (with-redefs [sync-databases-trigger/update-db-trigger-if-needed! (fn [_ _] (swap! calls inc))]
+ (mt/with-dynamic-fn-redefs [sync-databases-trigger/update-db-trigger-if-needed! (fn [_ _] (swap! calls inc))]
(testing "non-stub: triggers are considered for scheduling"
(reset! calls 0)
(sync-databases-trigger/check-and-schedule-tasks-for-db! non-stub)
diff --git a/test/metabase/test/util.clj b/test/metabase/test/util.clj
index a025d1372e6..8084ee9fafd 100644
--- a/test/metabase/test/util.clj
+++ b/test/metabase/test/util.clj
@@ -1047,18 +1047,18 @@
(let [attempts (atom 0)]
;; Diehard also consults `:retry-if` on success, with a nil exception — a `(constantly true)` stub would retry
;; the successful attempt too. The real predicate returns false for nil.
- (with-redefs [transient-error/transient-error? (fn [_db-type e] (some? e))
- search/reindex! (fn [& _]
- (when (= 1 (swap! attempts inc))
- (throw (java.sql.SQLException. "Deadlock detected"))))]
+ (dynamic-redefs/with-dynamic-fn-redefs [transient-error/transient-error? (fn [_db-type e] (some? e))
+ search/reindex! (fn [& _]
+ (when (= 1 (swap! attempts inc))
+ (throw (java.sql.SQLException. "Deadlock detected"))))]
(#'reindex-search-index!)
(is (= 2 @attempts)))))
(testing "any other failure is not"
(let [attempts (atom 0)]
- (with-redefs [transient-error/transient-error? (constantly false)
- search/reindex! (fn [& _]
- (swap! attempts inc)
- (throw (java.sql.SQLException. "Syntax error")))]
+ (dynamic-redefs/with-dynamic-fn-redefs [transient-error/transient-error? (constantly false)
+ search/reindex! (fn [& _]
+ (swap! attempts inc)
+ (throw (java.sql.SQLException. "Syntax error")))]
(is (thrown? java.sql.SQLException (#'reindex-search-index!)))
(is (= 1 @attempts))))))
diff --git a/test/metabase/tiles/api_test.clj b/test/metabase/tiles/api_test.clj
index 30049772532..18449adceed 100644
--- a/test/metabase/tiles/api_test.clj
+++ b/test/metabase/tiles/api_test.clj
@@ -254,8 +254,8 @@
(deftest breakout-query-test
(testing "the appropriate lat/lon fields are selected from the results, if the query contains a :breakout clause (#20182)"
(mt/dataset test-data
- (with-redefs [api.tiles/create-tile (fn [_ points] points)
- api.tiles/tile->byte-array identity]
+ (mt/with-dynamic-fn-redefs [api.tiles/create-tile (fn [_ points] points)
+ api.tiles/tile->byte-array identity]
(let [result (mt/user-http-request
:crowberto :get 200 "tiles/7/30/49"
:latField (encoded-lat-field-ref :mbql)
diff --git a/test/metabase/transforms/jobs_test.clj b/test/metabase/transforms/jobs_test.clj
index c92bc9deefd..ffee6da399d 100644
--- a/test/metabase/transforms/jobs_test.clj
+++ b/test/metabase/transforms/jobs_test.clj
@@ -526,26 +526,26 @@
deps {1 #{} 2 #{1} 3 #{}}
ran (atom #{})]
(testing "a fresh pulled-in dep is not executed, but its dependent still runs"
- (with-redefs [freshness/fresh-dep-ids (fn [_now dep-ids]
- ;; only pulled-in deps are offered for gating
- (is (= #{1} (set dep-ids)))
- #{1})
- jobs/run-transform! (fn [_ _ t] (swap! ran conj (:id t)))]
+ (mt/with-dynamic-fn-redefs [freshness/fresh-dep-ids (fn [_now dep-ids]
+ ;; only pulled-in deps are offered for gating
+ (is (= #{1} (set dep-ids)))
+ #{1})
+ jobs/run-transform! (fn [_ _ t] (swap! ran conj (:id t)))]
(is (= {::jobs/status :succeeded}
(jobs/run-transforms! 0 #{2 3} {:order plan :deps deps} {:run-method :cron})))
(is (= #{2 3} @ran) "transform 1 (fresh dep) was skipped; 2 and 3 ran")))
(testing "skip-fresh-deps? false (manual run_all) force-refreshes the whole plan"
(reset! ran #{})
- (with-redefs [freshness/fresh-dep-ids (fn [& _] (throw (ex-info "must not gate when disabled" {})))
- jobs/run-transform! (fn [_ _ t] (swap! ran conj (:id t)))]
+ (mt/with-dynamic-fn-redefs [freshness/fresh-dep-ids (fn [& _] (throw (ex-info "must not gate when disabled" {})))
+ jobs/run-transform! (fn [_ _ t] (swap! ran conj (:id t)))]
(is (= {::jobs/status :succeeded}
(jobs/run-transforms! 0 #{2 3} {:order plan :deps deps}
{:run-method :manual :skip-fresh-deps? false})))
(is (= #{1 2 3} @ran) "with skipping disabled, the dep runs too"))))
(testing "a plan that is entirely skipped exits cleanly as succeeded with nothing run"
(let [ran (atom #{})]
- (with-redefs [freshness/fresh-dep-ids (fn [_now _dep-ids] #{1})
- jobs/run-transform! (fn [_ _ t] (swap! ran conj (:id t)))]
+ (mt/with-dynamic-fn-redefs [freshness/fresh-dep-ids (fn [_now _dep-ids] #{1})
+ jobs/run-transform! (fn [_ _ t] (swap! ran conj (:id t)))]
(is (= {::jobs/status :succeeded}
(jobs/run-transforms! 0 #{} {:order [{:id 1}] :deps {1 #{}}} {:run-method :cron})))
(is (= #{} @ran)))))))
@@ -633,8 +633,8 @@
deps {1 #{} 2 #{} 3 #{} 4 #{}}
barrier (CyclicBarrier. 4)]
(mt/with-temporary-setting-values [transforms.settings/transform-run-job-sql-concurrency 4]
- (with-redefs [jobs/run-transform! (fn [_ _ _]
- (.await barrier 5 TimeUnit/SECONDS))]
+ (mt/with-dynamic-fn-redefs [jobs/run-transform! (fn [_ _ _]
+ (.await barrier 5 TimeUnit/SECONDS))]
(is (= {::jobs/status :succeeded}
(jobs/run-transforms! 0 #{1 2 3 4} {:order plan :deps deps} {:run-method :manual}))
"all four independents must reach the barrier (i.e. be live simultaneously)")))))
@@ -643,19 +643,19 @@
deps {1 #{} 2 #{1}}
order (atom [])]
(mt/with-temporary-setting-values [transforms.settings/transform-run-job-sql-concurrency 4]
- (with-redefs [jobs/run-transform! (fn [_ _ transform]
- (when (= 1 (:id transform))
- (Thread/sleep 100))
- (swap! order conj (:id transform)))]
+ (mt/with-dynamic-fn-redefs [jobs/run-transform! (fn [_ _ transform]
+ (when (= 1 (:id transform))
+ (Thread/sleep 100))
+ (swap! order conj (:id transform)))]
(jobs/run-transforms! 0 #{1 2} {:order plan :deps deps} {:run-method :manual})
(is (= [1 2] @order) "a must complete before b starts")))))
(testing "Dependents of a failed transform are skipped transitively"
(let [plan [{:id 1} {:id 2} {:id 3}]
deps {1 #{} 2 #{1} 3 #{2}}]
(mt/with-temporary-setting-values [transforms.settings/transform-run-job-sql-concurrency 4]
- (with-redefs [jobs/run-transform! (fn [_ _ transform]
- (when (= 1 (:id transform))
- (throw (ex-info "boom" {}))))]
+ (mt/with-dynamic-fn-redefs [jobs/run-transform! (fn [_ _ transform]
+ (when (= 1 (:id transform))
+ (throw (ex-info "boom" {}))))]
(let [result (jobs/run-transforms! 0 #{1 2 3} {:order plan :deps deps} {:run-method :manual})]
(is (= :failed (::jobs/status result)))
(is (= #{1 2 3} (set (map (comp :id ::jobs/transform) (::jobs/failures result))))
@@ -669,11 +669,11 @@
live (atom 0)
max-live (atom 0)]
(mt/with-temporary-setting-values [transforms.settings/transform-run-job-sql-concurrency 2]
- (with-redefs [jobs/run-transform! (fn [_ _ _]
- (let [n (swap! live inc)]
- (swap! max-live max n))
- (.await partner-up 5 TimeUnit/SECONDS)
- (swap! live dec))]
+ (mt/with-dynamic-fn-redefs [jobs/run-transform! (fn [_ _ _]
+ (let [n (swap! live inc)]
+ (swap! max-live max n))
+ (.await partner-up 5 TimeUnit/SECONDS)
+ (swap! live dec))]
(jobs/run-transforms! 0 (set (range 1 9)) {:order plan :deps deps} {:run-method :manual})
(is (= 2 @max-live) "should never exceed the concurrency setting")))))
(testing "Python transforms are serialized in their own lane (n=1)"
@@ -683,13 +683,13 @@
live (atom 0)
max-live (atom 0)]
(mt/with-temporary-setting-values [transforms.settings/transform-run-job-sql-concurrency 4]
- (with-redefs [jobs/run-transform! (fn [_ _ _]
- (let [n (swap! live inc)]
- (swap! max-live max n))
- ;; A short sleep gives any (hypothetical) parallel
- ;; python worker a window to show up in the counter.
- (Thread/sleep 50)
- (swap! live dec))]
+ (mt/with-dynamic-fn-redefs [jobs/run-transform! (fn [_ _ _]
+ (let [n (swap! live inc)]
+ (swap! max-live max n))
+ ;; A short sleep gives any (hypothetical) parallel
+ ;; python worker a window to show up in the counter.
+ (Thread/sleep 50)
+ (swap! live dec))]
(jobs/run-transforms! 0 #{1 2 3 4} {:order plan :deps deps} {:run-method :manual})
(is (= 1 @max-live)
"python transforms must run one at a time even with concurrency=4")))))
@@ -702,13 +702,13 @@
py-live (atom 0)
max-py (atom 0)]
(mt/with-temporary-setting-values [transforms.settings/transform-run-job-sql-concurrency 3]
- (with-redefs [jobs/run-transform! (fn [_ _ transform]
- (if (= :python (-> transform :source :type))
- (do (let [n (swap! py-live inc)]
- (swap! max-py max n))
- (Thread/sleep 50)
- (swap! py-live dec))
- (.await sql-barrier 5 TimeUnit/SECONDS)))]
+ (mt/with-dynamic-fn-redefs [jobs/run-transform! (fn [_ _ transform]
+ (if (= :python (-> transform :source :type))
+ (do (let [n (swap! py-live inc)]
+ (swap! max-py max n))
+ (Thread/sleep 50)
+ (swap! py-live dec))
+ (.await sql-barrier 5 TimeUnit/SECONDS)))]
(is (= {::jobs/status :succeeded}
(jobs/run-transforms! 0 #{1 2 3 4 5} {:order plan :deps deps} {:run-method :manual}))
"all three SQL transforms reach the barrier (run in parallel)")
diff --git a/test/metabase/transforms_base/util_test.clj b/test/metabase/transforms_base/util_test.clj
index b8e22accdb5..0d6fb87efbe 100644
--- a/test/metabase/transforms_base/util_test.clj
+++ b/test/metabase/transforms_base/util_test.clj
@@ -77,7 +77,7 @@
(mt/with-temp [:model/Table _ {:db_id (mt/id)
:schema nil
:name "disable_auto_sync_target"}]
- (with-redefs [sync/sync-table! (fn [_] (swap! calls inc))]
+ (mt/with-dynamic-fn-redefs [sync/sync-table! (fn [_] (swap! calls inc))]
(mt/with-temporary-setting-values [disable-auto-sync true]
(transforms-base.u/activate-table-and-mark-computed!
(mt/db)
diff --git a/test/metabase/typed_schemas/schema/metric_test.clj b/test/metabase/typed_schemas/schema/metric_test.clj
index 36fc2cf3f0d..48075ec5b34 100644
--- a/test/metabase/typed_schemas/schema/metric_test.clj
+++ b/test/metabase/typed_schemas/schema/metric_test.clj
@@ -82,39 +82,39 @@
(ex-data exception))))))
(deftest metric-schemas-excludes-card-sourced-metrics-test
- (with-redefs [schema.common/select-schema-cards
- (constantly [{:id 247
- :dataset_query {:lib/type :mbql/query
- :database 1
- :stages [{:lib/type :mbql.stage/mbql
- :source-table 10}]}}
- {:id 258
- :dataset_query {:query {:source-table "card__42"}}}
- {:id 259
- :dataset_query {:stages [{:source-card 42}]}}])
- schema.metric/metric-details identity
- schema.metric/metric-schema (fn [details _card] (:id details))]
+ (mt/with-dynamic-fn-redefs [schema.common/select-schema-cards
+ (constantly [{:id 247
+ :dataset_query {:lib/type :mbql/query
+ :database 1
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table 10}]}}
+ {:id 258
+ :dataset_query {:query {:source-table "card__42"}}}
+ {:id 259
+ :dataset_query {:stages [{:source-card 42}]}}])
+ schema.metric/metric-details identity
+ schema.metric/metric-schema (fn [details _card] (:id details))]
(is (= [247]
(vec (schema.metric/metric-schemas nil nil))))))
(deftest metric-schemas-excludes-metrics-that-reference-other-metrics-test
- (with-redefs [schema.common/select-schema-cards
- (constantly [{:id 247
- :dataset_query {:lib/type :mbql/query
- :database 1
- :stages [{:lib/type :mbql.stage/mbql
- :source-table 10}]}}
- {:id 258
- :dataset_query {:lib/type :mbql/query
- :database 1
- :stages [{:lib/type :mbql.stage/mbql
- :source-table 10
- :aggregation [[:metric
- {:lib/uuid
- "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"}
- 247]]}]}}])
- schema.metric/metric-details identity
- schema.metric/metric-schema (fn [details _card] (:id details))]
+ (mt/with-dynamic-fn-redefs [schema.common/select-schema-cards
+ (constantly [{:id 247
+ :dataset_query {:lib/type :mbql/query
+ :database 1
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table 10}]}}
+ {:id 258
+ :dataset_query {:lib/type :mbql/query
+ :database 1
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table 10
+ :aggregation [[:metric
+ {:lib/uuid
+ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"}
+ 247]]}]}}])
+ schema.metric/metric-details identity
+ schema.metric/metric-schema (fn [details _card] (:id details))]
(is (= [247]
(vec (schema.metric/metric-schemas nil nil))))))
@@ -122,28 +122,28 @@
;; Metric 258 is table-sourced and joins a saved question, so `source-card-id` — which only reads
;; stage 0's source — passes it. The CLI checks the whole query and rejects it, aborting
;; `sync-resources` for any app that uses it, so codegen has to drop it here as well.
- (with-redefs [schema.common/select-schema-cards
- (constantly [{:id 247
- :dataset_query {:lib/type :mbql/query
- :database 1
- :stages [{:lib/type :mbql.stage/mbql
- :source-table 10}]}}
- {:id 258
- :dataset_query {:lib/type :mbql/query
- :database 1
- :stages [{:lib/type :mbql.stage/mbql
- :source-table 10
- :joins [{:lib/type :mbql/join
- :alias "Question"
- :stages [{:lib/type :mbql.stage/mbql
- :source-card 42}]
- :conditions
- [[:=
- {:lib/uuid "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"}
- [:field {:lib/uuid "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"} 11]
- [:field {:lib/uuid "cccccccc-cccc-cccc-cccc-cccccccccccc"} 12]]]}]}]}}])
- schema.metric/metric-details identity
- schema.metric/metric-schema (fn [details _card] (:id details))]
+ (mt/with-dynamic-fn-redefs [schema.common/select-schema-cards
+ (constantly [{:id 247
+ :dataset_query {:lib/type :mbql/query
+ :database 1
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table 10}]}}
+ {:id 258
+ :dataset_query {:lib/type :mbql/query
+ :database 1
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table 10
+ :joins [{:lib/type :mbql/join
+ :alias "Question"
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-card 42}]
+ :conditions
+ [[:=
+ {:lib/uuid "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"}
+ [:field {:lib/uuid "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"} 11]
+ [:field {:lib/uuid "cccccccc-cccc-cccc-cccc-cccccccccccc"} 12]]]}]}]}}])
+ schema.metric/metric-details identity
+ schema.metric/metric-schema (fn [details _card] (:id details))]
(is (= [247]
(vec (schema.metric/metric-schemas nil nil))))))
diff --git a/test/metabase/typed_schemas/schema/question_test.clj b/test/metabase/typed_schemas/schema/question_test.clj
index c6d9b87b50f..b560936a1e6 100644
--- a/test/metabase/typed_schemas/schema/question_test.clj
+++ b/test/metabase/typed_schemas/schema/question_test.clj
@@ -28,10 +28,10 @@
(fn [{:keys [report-id] :as options}]
(swap! report-details-calls conj options)
{:structured-output {:id report-id :result-columns []}})]
- (with-redefs [schema.common/select-schema-cards (constantly cards)
- entity-details/cards-details (fn [card-type database-id selected-cards _options]
- (swap! bulk-details-calls conj [card-type database-id selected-cards])
- (map #(assoc % :fields []) selected-cards))]
+ (mt/with-dynamic-fn-redefs [schema.common/select-schema-cards (constantly cards)
+ entity-details/cards-details (fn [card-type database-id selected-cards _options]
+ (swap! bulk-details-calls conj [card-type database-id selected-cards])
+ (map #(assoc % :fields []) selected-cards))]
(is (= [41 42]
(mapv :id (schema.question/question-schemas nil nil))))
(is (= [[:question 1 cards]]
diff --git a/test/metabase/typed_schemas_rest/api_test.clj b/test/metabase/typed_schemas_rest/api_test.clj
index 51b9fc03688..1b8b11213e5 100644
--- a/test/metabase/typed_schemas_rest/api_test.clj
+++ b/test/metabase/typed_schemas_rest/api_test.clj
@@ -30,8 +30,8 @@
(is (not (str/includes? (:body response) "verified: false")))))
(deftest query-params-are-decoded-at-endpoint-test
- (with-redefs [typed-schemas/build-semantic-schema identity
- typed-schemas/render-typescript pr-str]
+ (mt/with-dynamic-fn-redefs [typed-schemas/build-semantic-schema identity
+ typed-schemas/render-typescript pr-str]
(let [response (-> (mt/user-http-request-full-response
:crowberto
:get
diff --git a/test/metabase/usage_metadata/batch_test.clj b/test/metabase/usage_metadata/batch_test.clj
index 2e28965e85f..c819bc0bbc9 100644
--- a/test/metabase/usage_metadata/batch_test.clj
+++ b/test/metabase/usage_metadata/batch_test.clj
@@ -285,7 +285,7 @@
old-day (t/local-date "2026-04-10")
valid-query (orders-query)
query-hash (lib-be.hash/query-hash valid-query)
- original usage-metadata.store/replace-day!]
+ original (mt/original-fn #'usage-metadata.store/replace-day!)]
(try
(doseq [day [day-a day-b old-day]]
(delete-query-executions-for-day! day)
@@ -303,10 +303,10 @@
:count 1})
(mt/with-temporary-setting-values [usage-metadata-last-completed-day nil
usage-metadata-retention-days 2]
- (with-redefs [usage-metadata.store/replace-day! (fn [bucket-date payload]
- (if (= bucket-date day-b)
- (throw (ex-info "boom" {:bucket-date bucket-date}))
- (original bucket-date payload)))]
+ (mt/with-dynamic-fn-redefs [usage-metadata.store/replace-day! (fn [bucket-date payload]
+ (if (= bucket-date day-b)
+ (throw (ex-info "boom" {:bucket-date bucket-date}))
+ (original bucket-date payload)))]
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"boom"
(usage-metadata.batch/run-batch!
{:today (t/local-date "2026-04-15")
@@ -328,7 +328,7 @@
good-hash (lib-be.hash/query-hash good-query)
bad-hash (.getBytes "bad-query" StandardCharsets/UTF_8)
bad-payload {:cooked :poison}
- original lib-be/normalize-query]
+ original (mt/original-fn #'lib-be/normalize-query)]
(try
(delete-query-executions-for-day! bucket-date)
(delete-day! bucket-date)
@@ -362,7 +362,7 @@
day-b (t/local-date "2026-04-14")
valid-query (orders-query)
query-hash (lib-be.hash/query-hash valid-query)
- original usage-metadata.store/replace-day!]
+ original (mt/original-fn #'usage-metadata.store/replace-day!)]
(try
(doseq [day [day-a day-b]]
(delete-query-executions-for-day! day)
@@ -372,10 +372,10 @@
(insert-query-execution! query-hash (t/offset-date-time "2026-04-14T12:00Z"))
(mt/with-temporary-setting-values [usage-metadata-last-completed-day nil
usage-metadata-retention-days 2]
- (with-redefs [usage-metadata.store/replace-day! (fn [bucket-date payload]
- (if (= bucket-date day-b)
- (throw (ex-info "boom" {:bucket-date bucket-date}))
- (original bucket-date payload)))]
+ (mt/with-dynamic-fn-redefs [usage-metadata.store/replace-day! (fn [bucket-date payload]
+ (if (= bucket-date day-b)
+ (throw (ex-info "boom" {:bucket-date bucket-date}))
+ (original bucket-date payload)))]
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"boom"
(usage-metadata.batch/run-batch!
{:today (t/local-date "2026-04-15")
diff --git a/test/metabase/usage_metadata/core_test.clj b/test/metabase/usage_metadata/core_test.clj
index d54962ce6ba..3aa163a5f33 100644
--- a/test/metabase/usage_metadata/core_test.clj
+++ b/test/metabase/usage_metadata/core_test.clj
@@ -1,6 +1,7 @@
(ns metabase.usage-metadata.core-test
(:require
[clojure.test :refer :all]
+ [metabase.test.util.dynamic-redefs :as dynamic-redefs]
[metabase.usage-metadata.core :as usage-metadata]
[metabase.usage-metadata.insights :as insights]))
@@ -36,10 +37,10 @@
(deftest implicit-segments-delegate-to-insights-test
(let [captured-args (atom nil)]
- (with-redefs [insights/implicit-segments
- (fn [opts]
- (reset! captured-args opts)
- [sample-segment])]
+ (dynamic-redefs/with-dynamic-fn-redefs [insights/implicit-segments
+ (fn [opts]
+ (reset! captured-args opts)
+ [sample-segment])]
(is (= [sample-segment]
(usage-metadata/implicit-segments {:source-type :card, :source-id 99, :limit 3})))
(is (= {:source-type :card, :source-id 99, :limit 3}
@@ -47,10 +48,10 @@
(deftest implicit-metrics-delegate-to-insights-test
(let [captured-args (atom nil)]
- (with-redefs [insights/implicit-metrics
- (fn [opts]
- (reset! captured-args opts)
- [sample-metric])]
+ (dynamic-redefs/with-dynamic-fn-redefs [insights/implicit-metrics
+ (fn [opts]
+ (reset! captured-args opts)
+ [sample-metric])]
(is (= [sample-metric]
(usage-metadata/implicit-metrics {:source-type :table, :source-id 42, :limit 7})))
(is (= {:source-type :table, :source-id 42, :limit 7}
@@ -58,10 +59,10 @@
(deftest implicit-dimensions-delegate-to-insights-test
(let [captured-args (atom nil)]
- (with-redefs [insights/implicit-dimensions
- (fn [opts]
- (reset! captured-args opts)
- [sample-dimension])]
+ (dynamic-redefs/with-dynamic-fn-redefs [insights/implicit-dimensions
+ (fn [opts]
+ (reset! captured-args opts)
+ [sample-dimension])]
(is (= [sample-dimension]
(usage-metadata/implicit-dimensions {:source-type :table, :source-id 42, :limit 9})))
(is (= {:source-type :table, :source-id 42, :limit 9}
@@ -69,10 +70,10 @@
(deftest suggested-segments-delegate-to-insights-test
(let [captured-args (atom nil)]
- (with-redefs [insights/suggested-segments-for-owner
- (fn [opts]
- (reset! captured-args opts)
- [sample-suggested-segment])]
+ (dynamic-redefs/with-dynamic-fn-redefs [insights/suggested-segments-for-owner
+ (fn [opts]
+ (reset! captured-args opts)
+ [sample-suggested-segment])]
(is (= [sample-suggested-segment]
(usage-metadata/suggested-segments {:source-type :table, :source-id 42, :limit 5})))
(is (= {:source-type :table, :source-id 42, :limit 5}
@@ -80,10 +81,10 @@
(deftest profile-observations-delegate-to-insights-test
(let [captured-args (atom nil)]
- (with-redefs [insights/profile-observations
- (fn [opts]
- (reset! captured-args opts)
- [sample-profile-observation])]
+ (dynamic-redefs/with-dynamic-fn-redefs [insights/profile-observations
+ (fn [opts]
+ (reset! captured-args opts)
+ [sample-profile-observation])]
(is (= [sample-profile-observation]
(usage-metadata/profile-observations {:source-type :table, :source-id 42, :limit 4})))
(is (= {:source-type :table, :source-id 42, :limit 4}
diff --git a/test/metabase/usage_metadata/store_test.clj b/test/metabase/usage_metadata/store_test.clj
index 197ba270d31..ee7872970e4 100644
--- a/test/metabase/usage_metadata/store_test.clj
+++ b/test/metabase/usage_metadata/store_test.clj
@@ -76,7 +76,7 @@
(try
(usage-metadata.store/delete-day! bucket-date)
(usage-metadata.store/replace-day! bucket-date original)
- (with-redefs [usage-metadata.store/insert-segment-rollups! (fn [_] (throw (ex-info "boom" {})))]
+ (mt/with-dynamic-fn-redefs [usage-metadata.store/insert-segment-rollups! (fn [_] (throw (ex-info "boom" {})))]
(is (thrown? clojure.lang.ExceptionInfo
(usage-metadata.store/replace-day! bucket-date original))))
(is (= #{"pred-a"}
diff --git a/test/metabase/usage_metadata/task/process_test.clj b/test/metabase/usage_metadata/task/process_test.clj
index 85294a11f37..e8194c07547 100644
--- a/test/metabase/usage_metadata/task/process_test.clj
+++ b/test/metabase/usage_metadata/task/process_test.clj
@@ -26,6 +26,8 @@
(mt/with-temp-scheduler!
(task/init! ::usage-metadata.task.process/UsageMetadataProcess)
(let [ran? (promise)]
+ ;; the job body runs on a Quartz scheduler thread, which doesn't inherit *local-redefs*
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [metabase.usage-metadata.batch/run-batch! (fn []
(deliver ran? true))]
(mt/with-temporary-setting-values [usage-metadata-enabled? false]
diff --git a/test/metabase/warehouse_schema/models/field_values_test.clj b/test/metabase/warehouse_schema/models/field_values_test.clj
index 4a8518d3641..4d71d64ddf1 100644
--- a/test/metabase/warehouse_schema/models/field_values_test.clj
+++ b/test/metabase/warehouse_schema/models/field_values_test.clj
@@ -842,7 +842,7 @@
:model/Field {f2-id :id} {:table_id table-id :name "dupe" :base_type :type/Integer
:parent_id parent-id}]
(let [fields [(t2/select-one :model/Field :id f1-id) (t2/select-one :model/Field :id f2-id)]]
- (with-redefs [qp/process-query (fn [_query] {:data {:rows [[0 "a"] [0 "b"] [1 "42"]]}})]
+ (mt/with-dynamic-fn-redefs [qp/process-query (fn [_query] {:data {:rows [[0 "a"] [0 "b"] [1 "42"]]}})]
(is (= {f1-id {:values ["a" "b"] :raw-count 2}
f2-id {:values [42] :raw-count 1}}
(distinct-batch/run-distinct-batch table fields))))))))
diff --git a/test/metabase/warehouse_schema_rest/api/field_test.clj b/test/metabase/warehouse_schema_rest/api/field_test.clj
index c6560b60406..0a3b3d759c1 100644
--- a/test/metabase/warehouse_schema_rest/api/field_test.clj
+++ b/test/metabase/warehouse_schema_rest/api/field_test.clj
@@ -915,10 +915,7 @@
(testing "reports a failed scan rather than answering success — a failed scan leaves the cached
FieldValues untouched, so there is otherwise no trace of it (GHY-2937)"
(mt/with-temp-vals-in-db :model/Field (mt/id :venues :price) {:has_field_values "list"}
- ;; `with-redefs`, not `mt/with-dynamic-fn-redefs`: `mt/user-http-request` issues a real HTTP request to the
- ;; test Jetty server, which handles it on a worker thread that does not inherit this thread's dynamic
- ;; bindings. Only a root rebind is visible there.
- (with-redefs [field-values/distinct-values (constantly nil)]
+ (mt/with-dynamic-fn-redefs [field-values/distinct-values (constantly nil)]
(is (=? {:message #"Failed to scan field values.*"}
(mt/user-http-request :crowberto :post 500
(format "field/%d/rescan_values" (mt/id :venues :price))))))))))
diff --git a/test/metabase/warehouses_rest/api_test.clj b/test/metabase/warehouses_rest/api_test.clj
index 856601110d4..4c1ac0669d5 100644
--- a/test/metabase/warehouses_rest/api_test.clj
+++ b/test/metabase/warehouses_rest/api_test.clj
@@ -1719,9 +1719,9 @@
(mt/with-temp [:model/Database {db-id :id} {:engine "h2", :details (:details (mt/db))}]
;; redefine quick-task/submit-task! so as not to depend on the capacity of the quick-task executor.
;; The Sync-now endpoint dispatches to the *explicit* sync fns (which bypass disable-auto-sync).
- (with-redefs [quick-task/submit-task! future-call
- sync-metadata/sync-db-metadata-explicit! (deliver-when-db sync-called? db-id)
- analyze/analyze-db-explicit! (deliver-when-db analyze-called? db-id)]
+ (mt/with-dynamic-fn-redefs [quick-task/submit-task! future-call
+ sync-metadata/sync-db-metadata-explicit! (deliver-when-db sync-called? db-id)
+ analyze/analyze-db-explicit! (deliver-when-db analyze-called? db-id)]
(snowplow-test/with-fake-snowplow-collector
(mt/user-http-request :crowberto :post 200 (format "database/%d/sync_schema" db-id))
;; Block waiting for the promises from sync and analyze to be delivered. Should be delivered instantly,
@@ -1756,9 +1756,9 @@
(mt/with-temp [:model/Database {db-id :id} {:engine "h2"
:details details
:initial_sync_status "incomplete"}]
- (with-redefs [quick-task/submit-task! (fn [f]
- (binding [driver.settings/*allow-testing-h2-connections* true]
- (f)))]
+ (mt/with-dynamic-fn-redefs [quick-task/submit-task! (fn [f]
+ (binding [driver.settings/*allow-testing-h2-connections* true]
+ (f)))]
(mt/user-http-request :crowberto :post 200 (format "database/%d/sync_schema" db-id)))
(testing "the explicit sync actually ran, not merely dispatched"
(is (= "complete" (t2/select-one-fn :initial_sync_status :model/Database :id db-id))