Skip to content

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

Audit driver/enterprise tests for with-dynamic-fn-redefs (#73940)

Chris Truterc1ede1fea3ab
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.edn
index 0471b712837..1b02c41b26c 100644
--- a/.clj-kondo/config.edn
+++ b/.clj-kondo/config.edn
@@ -800,14 +800,7 @@
:name general-qp-and-driver-test-namespaces}
{:pattern "(?:^mage.*)"
- :name mage-namespaces}
- ;;
- ;; Namespaces where `with-redefs` is still the idiom because they haven't been audited for conversion
- ;; to `with-dynamic-fn-redefs` yet (enterprise tests, driver tests). The linter's nudge is too noisy
- ;; here — audit can happen in follow-up PRs.
- ;;
- {:pattern "^(?:metabase-enterprise\\..+-test(?:\\..+)?|metabase\\.driver\\..+-test(?:\\..+)?)$"
- :name prefer-with-dynamic-fn-redefs-unaudited}]
+ :name mage-namespaces}]
:config-in-ns
{test-namespaces
@@ -831,10 +824,6 @@
metabase.util.time-test
{:linters {:metabase/prefer-with-dynamic-fn-redefs {:level :off}}}
- ;; Enterprise tests and driver tests haven't been audited yet — silence the linter so CI can ship.
- prefer-with-dynamic-fn-redefs-unaudited
- {:linters {:metabase/prefer-with-dynamic-fn-redefs {:level :off}}}
-
source-namespaces
{:linters
{:metabase/discourage-millis-duration {:level :warning}
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_permissions/api/setting_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_permissions/api/setting_test.clj
index f1521a3a715..9163fc1180f 100644
--- a/enterprise/backend/test/metabase_enterprise/advanced_permissions/api/setting_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/advanced_permissions/api/setting_test.clj
@@ -20,7 +20,7 @@
user [group]]
(letfn [(set-email-setting! [user status]
(testing (format "set email setting with %s user" (mt/user-descriptor user))
- (with-redefs [email/test-smtp-settings (constantly {::email/error nil})]
+ (mt/with-dynamic-fn-redefs [email/test-smtp-settings (constantly {::email/error nil})]
(mt/user-http-request user :put status "email" {:email-smtp-host "foobar"
:email-smtp-port "789"
:email-smtp-security :tls
@@ -67,10 +67,10 @@
user [group]]
(letfn [(set-slack-settings! [user status]
(testing (format "set slack setting with %s user" (mt/user-descriptor user))
- (with-redefs [slack/valid-token? (constantly true)
- slack/channel-exists? (constantly true)
- slack/refresh-channels-and-usernames! (constantly true)
- slack/refresh-channels-and-usernames-when-needed! (constantly true)]
+ (mt/with-dynamic-fn-redefs [slack/valid-token? (constantly true)
+ slack/channel-exists? (constantly true)
+ slack/refresh-channels-and-usernames! (constantly true)
+ slack/refresh-channels-and-usernames-when-needed! (constantly true)]
(mt/with-temporary-setting-values [slack-app-token nil]
(mt/user-http-request user :put status "slack/settings" {:slack-app-token "fake-token"})))))
(get-manifest [user status]
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj
index 9fec0885508..5bd1d5d530b 100644
--- a/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj
@@ -635,7 +635,7 @@
(testing "A non-admin with no data access can trigger a re-scan of field values if they have data model perms"
(t2/update! :model/FieldValues :field_id (mt/id :venues :price) {:values [10 20 30 40]})
(is (= [10 20 30 40] (t2/select-one-fn :values :model/FieldValues, :field_id (mt/id :venues :price))))
- (with-redefs [quick-task/submit-task! (fn [task] (task))]
+ (mt/with-dynamic-fn-redefs [quick-task/submit-task! (fn [task] (task))]
(mt/with-all-users-data-perms-graph! {(mt/id) {:view-data :blocked
:create-queries :no
:data-model {:schemas {"PUBLIC" {(mt/id :venues) :all}}}}}
@@ -749,7 +749,7 @@
(mt/test-helpers-set-global-values!
(mt/with-temp [:model/Database {db-id :id} {:engine "h2", :details (:details (mt/db))}]
;; Don't actually run the sync task in this test — just test the API-level permission enforcement
- (with-redefs [quick-task/submit-task! (constantly nil)]
+ (mt/with-dynamic-fn-redefs [quick-task/submit-task! (constantly nil)]
(testing "A non-admin cannot trigger a sync of the DB schema if they do not have DB details permissions"
(mt/with-all-users-data-perms-graph! {db-id {:details :no}}
(mt/user-http-request :rasta :post 403 (format "database/%d/sync_schema" db-id))))
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 fc5bbf3a1ac..5239cb59665 100644
--- a/enterprise/backend/test/metabase_enterprise/audit_app/audit_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/audit_app/audit_test.clj
@@ -90,7 +90,7 @@
db-id))]
(is (not (db-has-sync-job-trigger? audit/audit-db-id)))))
(testing "Audit DB doesn't get re-installed unless the engine changes"
- (with-redefs [ee.audit.settings/load-analytics-content (constantly nil)]
+ (mt/with-dynamic-fn-redefs [ee.audit.settings/load-analytics-content (constantly nil)]
(is (= ::ee-audit/no-op (ee-audit/ensure-audit-db-installed!)))
(t2/update! :model/Database :is_audit true {:engine "datomic"})
(is (= ::ee-audit/updated (ee-audit/ensure-audit-db-installed!)))
@@ -133,7 +133,7 @@
(is (= '("metabase.task.update-field-values.trigger.13371337")
(get-audit-db-trigger-keys))
"no sync scheduled after installation")
- (with-redefs [task.sync-databases/job-context->database-id (constantly audit/audit-db-id)]
+ (mt/with-dynamic-fn-redefs [task.sync-databases/job-context->database-id (constantly audit/audit-db-id)]
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
#"Cannot sync Database: It is the audit db."
@@ -167,7 +167,7 @@
(t2/delete! :model/Database :is_audit true)
(testing "If audit content loading throws an exception, the checksum should not be stored"
(audit/last-analytics-checksum! 0)
- (with-redefs [serialization.cmd/v2-load-internal! (fn [& _] (throw (Exception. "Audit loading failed")))]
+ (mt/with-dynamic-fn-redefs [serialization.cmd/v2-load-internal! (fn [& _] (throw (Exception. "Audit loading failed")))]
(is (thrown-with-msg? Exception
#"Audit loading failed"
(ee-audit/ensure-audit-db-installed!)))
@@ -201,9 +201,9 @@
(.putNextEntry out (JarEntry. (str resource "/" rel)))
(.write out (.getBytes ^String sql StandardCharsets/UTF_8))
(.closeEntry out)))
- (with-redefs [io/resource (fn [path]
- (when (= path resource)
- jar-url))]
+ (mt/with-dynamic-fn-redefs [io/resource (fn [path]
+ (when (= path resource)
+ jar-url))]
(is (= expected (#'ee-audit/views-checksum))))
(finally
(Files/deleteIfExists jar-path)))))
@@ -226,9 +226,9 @@
[jar-a url-a] (make-jar [["a.sql" "select 1;"]])
[jar-b url-b] (make-jar [["b.sql" "select 1;"]])]
(try
- (let [checksum-a (with-redefs [io/resource (constantly url-a)]
+ (let [checksum-a (mt/with-dynamic-fn-redefs [io/resource (constantly url-a)]
(#'ee-audit/views-checksum))
- checksum-b (with-redefs [io/resource (constantly url-b)]
+ checksum-b (mt/with-dynamic-fn-redefs [io/resource (constantly url-b)]
(#'ee-audit/views-checksum))]
(is (not= checksum-a checksum-b)))
(finally
@@ -239,9 +239,9 @@
(mt/with-temp [:model/Database audit-db {:engine "h2" :is_audit true}]
(let [checksum 12345]
(ee.audit.settings/last-analytics-views-checksum! 0)
- (with-redefs [ee-audit/views-checksum (constantly checksum)
- sync/sync-database! (fn [& _]
- (throw (Exception. "sync failed")))]
+ (mt/with-dynamic-fn-redefs [ee-audit/views-checksum (constantly checksum)
+ sync/sync-database! (fn [& _]
+ (throw (Exception. "sync failed")))]
(is (nil? (#'ee-audit/maybe-sync-audit-db! audit-db false)))
(is (= 0 (ee.audit.settings/last-analytics-views-checksum)))))))
diff --git a/enterprise/backend/test/metabase_enterprise/cache/strategies_test.clj b/enterprise/backend/test/metabase_enterprise/cache/strategies_test.clj
index 83b5eec67c3..fa5da52c669 100644
--- a/enterprise/backend/test/metabase_enterprise/cache/strategies_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/cache/strategies_test.clj
@@ -128,7 +128,7 @@
(testing "strategy = ttl"
(mt/with-model-cleanup [[:model/QueryCache :updated_at]]
(mt/with-clock (t 0)
- (let [q (with-redefs [query/average-execution-time-ms (constantly 1000)]
+ (let [q (mt/with-dynamic-fn-redefs [query/average-execution-time-ms (constantly 1000)]
(#'qp.card/query-for-card card1 [] {} {} {}))]
(is (=? {:type :ttl :multiplier 100}
(:cache-strategy q)))
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 76fba5ef9b9..55b30e8e0b1 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
@@ -31,12 +31,12 @@
401 "Could not establish a connection to Metabase Cloud."
400 "Could not purchase this add-on."}]
(testing (format "passes through HTTP status %d from Store API" status-code)
- (with-redefs [hm.client/call (fn [& _] (throw (ex-info "TEST" {:status status-code})))]
+ (mt/with-dynamic-fn-redefs [hm.client/call (fn [& _] (throw (ex-info "TEST" {:status status-code})))]
(is (=? error-message
(mt/user-http-request :crowberto :post status-code "ee/cloud-add-ons/metabase-ai"
{:terms_of_service true}))))))
(testing "responds with HTTP status 500 for other errors from Store API"
- (with-redefs [hm.client/call (fn [& _] (throw (ex-info "TEST" {})))]
+ (mt/with-dynamic-fn-redefs [hm.client/call (fn [& _] (throw (ex-info "TEST" {})))]
(is (=? "Unexpected error"
(mt/user-http-request :crowberto :post 500 "ee/cloud-add-ons/metabase-ai"
{:terms_of_service true})))))
@@ -100,11 +100,11 @@
401 "Could not establish a connection to Metabase Cloud."
400 "Could not remove this add-on."}]
(testing (format "passes through HTTP status %d from Store API" status-code)
- (with-redefs [hm.client/call (fn [& _] (throw (ex-info "TEST" {:status status-code})))]
+ (mt/with-dynamic-fn-redefs [hm.client/call (fn [& _] (throw (ex-info "TEST" {:status status-code})))]
(is (=? error-message
(mt/user-http-request :crowberto :delete status-code "ee/cloud-add-ons/metabase-ai-managed"))))))
(testing "responds with HTTP status 500 for other errors from Store API"
- (with-redefs [hm.client/call (fn [& _] (throw (ex-info "TEST" {})))]
+ (mt/with-dynamic-fn-redefs [hm.client/call (fn [& _] (throw (ex-info "TEST" {})))]
(is (=? "Unexpected error"
(mt/user-http-request :crowberto :delete 500 "ee/cloud-add-ons/metabase-ai-managed")))))
(testing "succeeds"
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 7937e9a150c..2715e832aa6 100644
--- a/enterprise/backend/test/metabase_enterprise/cloud_proxy/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/cloud_proxy/api_test.clj
@@ -81,9 +81,9 @@
(testing "request body keys are converted to kebab-case for harbormaster"
(mt/with-premium-features #{:hosting}
(let [received-body (atom nil)]
- (with-redefs [hm.client/call (fn [_op body]
- (reset! received-body body)
- {:status "ok"})]
+ (mt/with-dynamic-fn-redefs [hm.client/call (fn [_op body]
+ (reset! received-body body)
+ {:status "ok"})]
(mt/user-http-request :crowberto :post 200 "ee/cloud-proxy/mb-plan-change-plan-preview"
{:new_plan_alias "pro-cloud"
:force_end_trial true})
diff --git a/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/api_test.clj b/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/api_test.clj
index 212984475f8..610fb9f4062 100644
--- a/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/api_test.clj
@@ -323,8 +323,8 @@
(with-dev-mode-enabled
(mt/with-model-cleanup [:model/CustomVizPlugin]
(testing "dev plugin registration with manifest name"
- (with-redefs [cache/fetch-dev-manifest (constantly {:name "dev-chart" :icon "icon.svg"})
- cache/set-or-clear-dev-bundle! (constantly nil)]
+ (mt/with-dynamic-fn-redefs [cache/fetch-dev-manifest (constantly {:name "dev-chart" :icon "icon.svg"})
+ cache/set-or-clear-dev-bundle! (constantly nil)]
(let [resp (mt/user-http-request :crowberto :post 200 "ee/custom-viz-plugin/dev"
{:dev_bundle_url "http://localhost:5174"})]
(is (= "dev-chart" (:identifier resp)))
@@ -335,21 +335,21 @@
(is (= "active" (:status resp))
"dev plugins are immediately active"))))
(testing "dev plugin registration with explicit identifier overrides manifest"
- (with-redefs [cache/fetch-dev-manifest (constantly {:name "manifest-name"})
- cache/set-or-clear-dev-bundle! (constantly nil)]
+ (mt/with-dynamic-fn-redefs [cache/fetch-dev-manifest (constantly {:name "manifest-name"})
+ cache/set-or-clear-dev-bundle! (constantly nil)]
(let [resp (mt/user-http-request :crowberto :post 200 "ee/custom-viz-plugin/dev"
{:dev_bundle_url "http://localhost:5174"
:identifier "my-override"})]
(is (= "my-override" (:identifier resp))
"explicit identifier takes precedence over manifest name"))))
(testing "dev plugin registration fails with helpful message when no identifier and no manifest"
- (with-redefs [cache/fetch-dev-manifest (constantly nil)]
+ (mt/with-dynamic-fn-redefs [cache/fetch-dev-manifest (constantly nil)]
(let [resp (mt/user-http-request :crowberto :post 400 "ee/custom-viz-plugin/dev"
{:dev_bundle_url "http://localhost:5174"})]
(is (str/includes? resp "metabase-plugin.json")
"error should mention the manifest file"))))
(testing "dev plugin registration fails with helpful message when manifest missing name"
- (with-redefs [cache/fetch-dev-manifest (constantly {:icon "icon.svg"})]
+ (mt/with-dynamic-fn-redefs [cache/fetch-dev-manifest (constantly {:icon "icon.svg"})]
(let [resp (mt/user-http-request :crowberto :post 400 "ee/custom-viz-plugin/dev"
{:dev_bundle_url "http://localhost:5174"})]
(is (str/includes? resp "name")
@@ -413,8 +413,8 @@
:display_name "dev-refresh"
:status :active
:dev_bundle_url "http://localhost:5174"}]
- (with-redefs [cache/resolve-dev-bundle (constantly "http://localhost:5174")
- cache/fetch-dev-manifest (constantly {:name "Updated Name" :icon "new-icon.svg"})]
+ (mt/with-dynamic-fn-redefs [cache/resolve-dev-bundle (constantly "http://localhost:5174")
+ cache/fetch-dev-manifest (constantly {:name "Updated Name" :icon "new-icon.svg"})]
(let [resp (mt/user-http-request :crowberto :post 200 (str "ee/custom-viz-plugin/" id "/refresh"))]
(is (= "Updated Name" (:display_name resp))))))))))
@@ -489,13 +489,13 @@
:status :active
:bundle_hash "abc123"}]
(testing "returns bundle with correct content-type and ETag"
- (with-redefs [cache/resolve-dev-bundle (constantly nil)
- cache/resolve-bundle (constantly {:content "console.log('hello')" :hash "deadbeef"})]
+ (mt/with-dynamic-fn-redefs [cache/resolve-dev-bundle (constantly nil)
+ cache/resolve-bundle (constantly {:content "console.log('hello')" :hash "deadbeef"})]
(let [resp (mt/user-http-request :crowberto :get 200 (str "ee/custom-viz-plugin/" id "/bundle"))]
(is (= "console.log('hello')" resp)))))
(testing "returns 503 when bundle is not available"
- (with-redefs [cache/resolve-dev-bundle (constantly nil)
- cache/resolve-bundle (constantly nil)]
+ (mt/with-dynamic-fn-redefs [cache/resolve-dev-bundle (constantly nil)
+ cache/resolve-bundle (constantly nil)]
(let [resp (mt/user-http-request :crowberto :get 503 (str "ee/custom-viz-plugin/" id "/bundle"))]
(is (some? resp))))))))
@@ -506,8 +506,8 @@
:status :active
:enabled true
:bundle_hash "abc123"}]
- (with-redefs [cache/resolve-dev-bundle (constantly nil)
- cache/resolve-bundle (constantly {:content "console.log('hi')" :hash "h1"})]
+ (mt/with-dynamic-fn-redefs [cache/resolve-dev-bundle (constantly nil)
+ cache/resolve-bundle (constantly {:content "console.log('hi')" :hash "h1"})]
(testing "authenticated non-admin user can access /bundle"
(is (= "console.log('hi')"
(mt/user-http-request :rasta :get 200 (str "ee/custom-viz-plugin/" id "/bundle")))))
@@ -547,8 +547,8 @@
(with-dev-mode-enabled
(mt/with-model-cleanup [:model/CustomVizPlugin]
(testing "registering a dev plugin records a custom-viz-plugin-create audit event"
- (with-redefs [cache/fetch-dev-manifest (constantly {:name "audit-dev-chart" :icon "icon.svg"})
- cache/set-or-clear-dev-bundle! (constantly nil)]
+ (mt/with-dynamic-fn-redefs [cache/fetch-dev-manifest (constantly {:name "audit-dev-chart" :icon "icon.svg"})
+ cache/set-or-clear-dev-bundle! (constantly nil)]
(let [resp (mt/user-http-request :crowberto :post 200 "ee/custom-viz-plugin/dev"
{:dev_bundle_url "http://localhost:5174"})
entry (mt/latest-audit-log-entry "custom-viz-plugin-create" (:id resp))]
@@ -644,8 +644,8 @@
(testing "dev endpoints work when dev mode is enabled"
(with-dev-mode-enabled
(mt/with-model-cleanup [:model/CustomVizPlugin]
- (with-redefs [cache/fetch-dev-manifest (constantly {:name "gated-dev" :icon "icon.svg"})
- cache/set-or-clear-dev-bundle! (constantly nil)]
+ (mt/with-dynamic-fn-redefs [cache/fetch-dev-manifest (constantly {:name "gated-dev" :icon "icon.svg"})
+ cache/set-or-clear-dev-bundle! (constantly nil)]
(let [resp (mt/user-http-request :crowberto :post 200 "ee/custom-viz-plugin/dev"
{:dev_bundle_url "http://localhost:5174"})]
(is (= "gated-dev" (:identifier resp))))))))))
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 c230c4c1f47..c213fede5f8 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
@@ -217,7 +217,7 @@
(deftest resolve-bundle-dev-url-takes-precedence-test
(testing "resolve-bundle prefers dev URL over the uploaded bundle when both are present"
(mt/with-premium-features #{:custom-viz}
- (with-redefs [custom-viz.settings/custom-viz-plugin-dev-mode-enabled (constantly true)]
+ (mt/with-dynamic-fn-redefs [custom-viz.settings/custom-viz-plugin-dev-mode-enabled (constantly true)]
(mt/with-temp [:model/CustomVizPlugin {id :id} {:identifier "precedence"
:display_name "precedence"
:status :active
@@ -225,8 +225,8 @@
:dev_bundle_url "http://localhost:5174"}]
(let [dev-called? (atom false)
fs-called? (atom false)]
- (with-redefs [cache/fetch-dev-bundle (fn [_] (reset! dev-called? true) {:content "dev-js" :hash "d1"})
- cache/get-bundle (fn [_] (reset! fs-called? true) {:content "fs-js" :hash "g1"})]
+ (mt/with-dynamic-fn-redefs [cache/fetch-dev-bundle (fn [_] (reset! dev-called? true) {:content "dev-js" :hash "d1"})
+ cache/get-bundle (fn [_] (reset! fs-called? true) {:content "fs-js" :hash "g1"})]
(let [result (cache/resolve-bundle {:id id})]
(is (true? @dev-called?) "dev bundle fetch should be called")
(is (false? @fs-called?) "filesystem bundle should not be called when dev URL is set")
diff --git a/enterprise/backend/test/metabase_enterprise/data_complexity_score/api_test.clj b/enterprise/backend/test/metabase_enterprise/data_complexity_score/api_test.clj
index fd7d2ad4337..fa9287b1e41 100644
--- a/enterprise/backend/test/metabase_enterprise/data_complexity_score/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_complexity_score/api_test.clj
@@ -127,12 +127,12 @@
(deftest complexity-endpoint-force-recalculation-returns-fresh-score-test
(testing "superusers can trigger the expensive recompute path on demand"
(let [persisted? (atom nil)]
- (with-redefs [metabot-scope/internal-metabot-scope (constantly {})
- task.complexity-score/current-fingerprint (constantly "api-test-fp")
- complexity/complexity-scores (fn [& _] sample-score)
- data-complexity-score/record-score! (fn [fingerprint source stored-score]
- (reset! persisted? [fingerprint source stored-score])
- (with-sample-calculated-at stored-score))]
+ (mt/with-dynamic-fn-redefs [metabot-scope/internal-metabot-scope (constantly {})
+ task.complexity-score/current-fingerprint (constantly "api-test-fp")
+ complexity/complexity-scores (fn [& _] sample-score)
+ data-complexity-score/record-score! (fn [fingerprint source stored-score]
+ (reset! persisted? [fingerprint source stored-score])
+ (with-sample-calculated-at stored-score))]
(is (= (expected-response (with-sample-calculated-at sample-score))
(mt/user-http-request :crowberto :get 200 endpoint :force-recalculation true)))
(is (= ["api-test-fp" "appdb" sample-score] @persisted?)
@@ -141,13 +141,13 @@
(deftest ^:sequential complexity-endpoint-force-recalculation-advances-last-fingerprint-on-snowplow-publish-test
(testing "force recalculation mirrors the scheduled path's fingerprint gate — advance only when Snowplow accepted the event"
(mt/with-temporary-setting-values [data-complexity-scoring-last-fingerprint "stale"]
- (with-redefs [metabot-scope/internal-metabot-scope (constantly {})
- task.complexity-score/current-fingerprint (constantly "refresh-fp")
- data-complexity-score/record-score! (fn [& _] nil)
- complexity/complexity-scores
- (fn [& _]
- (with-meta sample-score
- {::complexity/snowplow-published? true}))]
+ (mt/with-dynamic-fn-redefs [metabot-scope/internal-metabot-scope (constantly {})
+ task.complexity-score/current-fingerprint (constantly "refresh-fp")
+ data-complexity-score/record-score! (fn [& _] nil)
+ complexity/complexity-scores
+ (fn [& _]
+ (with-meta sample-score
+ {::complexity/snowplow-published? true}))]
(mt/user-http-request :crowberto :get 200 endpoint :force-recalculation true)
(is (= "refresh-fp" (data-complexity-score.settings/data-complexity-scoring-last-fingerprint))
"successful Snowplow publish must advance the last-fingerprint so the next boot doesn't redundantly re-score")))))
@@ -155,13 +155,13 @@
(deftest ^:sequential complexity-endpoint-force-recalculation-keeps-fingerprint-stale-when-snowplow-publish-fails-test
(testing "force recalculation leaves the fingerprint stale when Snowplow didn't accept the event, so the next scheduled run retries"
(mt/with-temporary-setting-values [data-complexity-scoring-last-fingerprint "stale"]
- (with-redefs [metabot-scope/internal-metabot-scope (constantly {})
- task.complexity-score/current-fingerprint (constantly "refresh-fp")
- data-complexity-score/record-score! (fn [& _] nil)
- complexity/complexity-scores
- (fn [& _]
- (with-meta sample-score
- {::complexity/snowplow-published? false}))]
+ (mt/with-dynamic-fn-redefs [metabot-scope/internal-metabot-scope (constantly {})
+ task.complexity-score/current-fingerprint (constantly "refresh-fp")
+ data-complexity-score/record-score! (fn [& _] nil)
+ complexity/complexity-scores
+ (fn [& _]
+ (with-meta sample-score
+ {::complexity/snowplow-published? false}))]
(mt/user-http-request :crowberto :get 200 endpoint :force-recalculation true)
(is (= "stale" (data-complexity-score.settings/data-complexity-scoring-last-fingerprint))
"failed publish must preserve the stale fingerprint — same semantics as the scheduled path")))))
@@ -169,10 +169,10 @@
(deftest complexity-endpoint-force-recalculation-runs-when-scheduled-scoring-disabled-test
(testing "manual force recalculation does not reuse the scheduled scorer's enabled gate"
(mt/with-temporary-setting-values [data-complexity-scoring-enabled false]
- (with-redefs [metabot-scope/internal-metabot-scope (constantly {})
- task.complexity-score/current-fingerprint (constantly "api-test-fp")
- complexity/complexity-scores (fn [& _] sample-score)
- data-complexity-score/record-score! (fn [& _] nil)]
+ (mt/with-dynamic-fn-redefs [metabot-scope/internal-metabot-scope (constantly {})
+ task.complexity-score/current-fingerprint (constantly "api-test-fp")
+ complexity/complexity-scores (fn [& _] sample-score)
+ data-complexity-score/record-score! (fn [& _] nil)]
(is (= (expected-response sample-score)
(mt/user-http-request :crowberto :get 200 endpoint :force-recalculation true)))))))
@@ -184,7 +184,7 @@
;; same vector across catalogs preserves the library ⊆ universe pair invariant.
(mt/with-dynamic-fn-redefs [synonym-source/complexity-scores-opts
(constantly {:embedder random-synonym-embedder})]
- (with-redefs [data-complexity-score/record-score! (fn [& _] nil)]
+ (mt/with-dynamic-fn-redefs [data-complexity-score/record-score! (fn [& _] nil)]
(let [resp (mt/user-http-request :crowberto :get 200 endpoint :force-recalculation true)
leaf-path {:entity_count [:size :entity_count]
:field_count [:size :field_count]
@@ -238,7 +238,7 @@
(mt/with-premium-features #{}
(mt/with-temp-vals-in-db :model/Metabot (internal-metabot-id)
{:use_verified_content false :collection_id nil}
- (with-redefs [data-complexity-score/record-score! (fn [& _] nil)]
+ (mt/with-dynamic-fn-redefs [data-complexity-score/record-score! (fn [& _] nil)]
(let [resp (mt/user-http-request :crowberto :get 200 endpoint :force-recalculation true)]
(is (= (:universe resp) (:metabot resp))))))))
(testing ":metabot is scored separately when :content-verification + use_verified_content are both active"
@@ -253,7 +253,7 @@
:archived false}]
(mt/with-temp-vals-in-db :model/Metabot (internal-metabot-id)
{:use_verified_content true :collection_id nil}
- (with-redefs [data-complexity-score/record-score! (fn [& _] nil)]
+ (mt/with-dynamic-fn-redefs [data-complexity-score/record-score! (fn [& _] nil)]
(let [resp (mt/user-http-request :crowberto :get 200 endpoint :force-recalculation true)]
(is (< (get-in resp [:metabot :components :size :components :entity_count :measurement])
(get-in resp [:universe :components :size :components :entity_count :measurement]))
@@ -300,7 +300,7 @@
(mt/with-temp-vals-in-db :model/Metabot (internal-metabot-id)
{:use_verified_content false
:collection_id cid}
- (with-redefs [data-complexity-score/record-score! (fn [& _] nil)]
+ (mt/with-dynamic-fn-redefs [data-complexity-score/record-score! (fn [& _] nil)]
(let [resp (mt/user-http-request :crowberto :get 200 endpoint :force-recalculation true)]
{:metabot (get-in resp [:metabot :components :size :components :entity_count :measurement])
:universe (get-in resp [:universe :components :size :components :entity_count :measurement])}))))
@@ -352,13 +352,13 @@
:owner "scheduled-owner"})
scoring-ran? (atom false)]
(mt/with-temporary-setting-values [data-complexity-scoring-claim active-claim]
- (with-redefs [metabot-scope/internal-metabot-scope (constantly {})
- task.complexity-score/current-fingerprint (constantly "api-test-fp")
- data-complexity-score/record-score! (fn [& _] nil)
- complexity/complexity-scores
- (fn [& _]
- (reset! scoring-ran? true)
- stub-scores)]
+ (mt/with-dynamic-fn-redefs [metabot-scope/internal-metabot-scope (constantly {})
+ task.complexity-score/current-fingerprint (constantly "api-test-fp")
+ data-complexity-score/record-score! (fn [& _] nil)
+ complexity/complexity-scores
+ (fn [& _]
+ (reset! scoring-ran? true)
+ stub-scores)]
(is (= (expected-response stub-scores)
(mt/user-http-request :crowberto :get 200 endpoint :force-recalculation true)))
(is (true? @scoring-ran?)
@@ -373,15 +373,15 @@
(let [release-scoring (CountDownLatch. 1)
scoring-started (CountDownLatch. 1)
call-count (atom 0)]
- (with-redefs [metabot-scope/internal-metabot-scope (constantly {})
- task.complexity-score/current-fingerprint (constantly "api-test-fp")
- data-complexity-score/record-score! (fn [& _] nil)
- complexity/complexity-scores
- (fn [& _]
- (swap! call-count inc)
- (.countDown scoring-started)
- (.await release-scoring 10 TimeUnit/SECONDS)
- stub-scores)]
+ (mt/with-dynamic-fn-redefs [metabot-scope/internal-metabot-scope (constantly {})
+ task.complexity-score/current-fingerprint (constantly "api-test-fp")
+ data-complexity-score/record-score! (fn [& _] nil)
+ complexity/complexity-scores
+ (fn [& _]
+ (swap! call-count inc)
+ (.countDown scoring-started)
+ (.await release-scoring 10 TimeUnit/SECONDS)
+ stub-scores)]
(let [first-request (future (mt/user-http-request :crowberto :get 200 endpoint :force-recalculation true))]
(try
(is (.await scoring-started 10 TimeUnit/SECONDS)
diff --git a/enterprise/backend/test/metabase_enterprise/data_studio/api/permissions_groups_test.clj b/enterprise/backend/test/metabase_enterprise/data_studio/api/permissions_groups_test.clj
index 3ee7df9353b..e3fad0f93f2 100644
--- a/enterprise/backend/test/metabase_enterprise/data_studio/api/permissions_groups_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_studio/api/permissions_groups_test.clj
@@ -34,7 +34,7 @@
(deftest sync-data-analyst-group-for-oss!-ee-noop-test
(testing "When we canonically have the feature, sync-data-analyst-group-for-oss! does nothing"
- (with-redefs [token-check/canonically-has-feature? (constantly true)]
+ (mt/with-dynamic-fn-redefs [token-check/canonically-has-feature? (constantly true)]
(let [data-analyst-group-id (:id (perms-group/data-analyst))]
(mt/with-temp [:model/User {user-id :id} {}]
(perms/add-user-to-group! user-id data-analyst-group-id)
@@ -49,7 +49,7 @@
(deftest sync-data-analyst-group-for-oss!-converts-with-members-test
(testing "When canonically lacking the feature, sync-data-analyst-group-for-oss! converts the Data Analysts group when it has members"
- (with-redefs [token-check/canonically-has-feature? (constantly false)]
+ (mt/with-dynamic-fn-redefs [token-check/canonically-has-feature? (constantly false)]
(with-reset-data-analyst-group!
(let [original-group-id (t2/select-one-pk :model/PermissionsGroup :magic_group_type perms-group/data-analyst-magic-group-type)]
(mt/with-temp [:model/User {user-id :id} {}]
@@ -72,7 +72,7 @@
(deftest sync-data-analyst-group-for-oss!-preserves-name-test
(testing "When the magic group has a non-default name (e.g. from a migration conflict), the new magic group keeps that name"
- (with-redefs [token-check/canonically-has-feature? (constantly false)]
+ (mt/with-dynamic-fn-redefs [token-check/canonically-has-feature? (constantly false)]
(with-reset-data-analyst-group!
(let [original-group-id (t2/select-one-pk :model/PermissionsGroup :magic_group_type perms-group/data-analyst-magic-group-type)]
;; Simulate the migration conflict scenario: rename the magic group to the fallback name
@@ -92,7 +92,7 @@
(deftest sync-data-analyst-group-for-oss!-idempotent-empty-test
(testing "Sync is idempotent when magic group is empty (no members to convert)"
- (with-redefs [token-check/canonically-has-feature? (constantly false)]
+ (mt/with-dynamic-fn-redefs [token-check/canonically-has-feature? (constantly false)]
(with-reset-data-analyst-group!
(let [group-count-before (t2/count :model/PermissionsGroup)
data-analyst-group-id (t2/select-one-pk :model/PermissionsGroup :magic_group_type perms-group/data-analyst-magic-group-type)]
diff --git a/enterprise/backend/test/metabase_enterprise/database_replication/api_test.clj b/enterprise/backend/test/metabase_enterprise/database_replication/api_test.clj
index c140f512532..b3ba7ab703c 100644
--- a/enterprise/backend/test/metabase_enterprise/database_replication/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/database_replication/api_test.clj
@@ -50,16 +50,16 @@
(is (= "PG replication is only supported for PostgreSQL databases."
(mt/user-http-request :crowberto :post 400 (str "ee/database-replication/connection/" (:id mysql-db)))))
(let [url (str "ee/database-replication/connection/" (:id postgres-db))]
- (with-redefs [hm.client/call (constantly [{:id 123, :type "pg_replication"}])]
+ (mt/with-dynamic-fn-redefs [hm.client/call (constantly [{:id 123, :type "pg_replication"}])]
(mt/with-temporary-setting-values [database-replication-connections {(:id postgres-db) {:connection-id 123}}]
(is (= "Database already has an active replication connection." (mt/user-http-request :crowberto :post 400 url)))))
- (with-redefs [hm.client/call (fn [& _] (throw (ex-info "test err" {})))]
+ (mt/with-dynamic-fn-redefs [hm.client/call (fn [& _] (throw (ex-info "test err" {})))]
(is (mt/user-http-request :crowberto :post 500 url))))))))
(deftest delete-fail-test
(mt/with-premium-features #{:attached-dwh :etl-connections :etl-connections-pg :hosting}
(mt/with-temporary-setting-values [is-hosted? true, store-api-url "foo", api-key "foo"]
- (with-redefs [hm.client/call (fn [& _] (throw (ex-info "test err" {})))]
+ (mt/with-dynamic-fn-redefs [hm.client/call (fn [& _] (throw (ex-info "test err" {})))]
(is (mt/user-http-request :crowberto :delete 500 "ee/database-replication/connection/99"))))))
(deftest lifecycle-test
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/api_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/api_test.clj
index e0e22f07c33..06b27b19faa 100644
--- a/enterprise/backend/test/metabase_enterprise/dependencies/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/api_test.clj
@@ -682,7 +682,7 @@
:content "SELECT 1"
:creator_id (mt/user->id :crowberto)}]
;; remove native permissions
- (with-redefs [snippet.perms/has-any-native-permissions? (constantly false)]
+ (mt/with-dynamic-fn-redefs [snippet.perms/has-any-native-permissions? (constantly false)]
(testing "Returns 403 when user lacks native query execution permissions"
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :post 403 "ee/dependencies/check-snippet"
@@ -724,8 +724,8 @@
:dataset_query (:dataset_query base-card)}]
(deps.test/synchronously-run-backfill!)
;; Mock errors-from-proposed-edits to report the transform as broken
- (with-redefs [dependencies/errors-from-proposed-edits
- (constantly {:transform {(:id transform) #{:some-error}}})]
+ (mt/with-dynamic-fn-redefs [dependencies/errors-from-proposed-edits
+ (constantly {:transform {(:id transform) #{:some-error}}})]
(testing "Admin sees broken transforms in response"
(let [response (mt/user-http-request :crowberto :post 200 "ee/dependencies/check-card"
proposed-card)]
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/events_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/events_test.clj
index 61d411c75ad..3fefd1545e4 100644
--- a/enterprise/backend/test/metabase_enterprise/dependencies/events_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/events_test.clj
@@ -271,8 +271,8 @@
(fn [mp]
(let [products (lib.metadata/table mp (mt/id :products))]
(mt/with-temp [:model/Card {card-id :id :as card} {:dataset_query (lib/query mp products)}]
- (with-redefs [deps.dependency-status/mark-stale!
- (fn [_ _] (throw (ex-info "Simulated DB failure" {})))]
+ (mt/with-dynamic-fn-redefs [deps.dependency-status/mark-stale!
+ (fn [_ _] (throw (ex-info "Simulated DB failure" {})))]
;; Should not throw — the error is caught and logged
(events/publish-event! :event/card-create {:object card :user-id api/*current-user-id*}))
;; Entity should NOT be stale (mark-stale! failed)
@@ -698,8 +698,8 @@
:analyzed_entity_type :card
:analyzed_entity_id card-id))))
(binding [models.analysis-finding/*current-analysis-finding-version* new-version]
- (with-redefs [deps.findings/mark-immediate-dependents-stale!
- (fn [_ _] (throw (ex-info "Simulated failure" {})))]
+ (mt/with-dynamic-fn-redefs [deps.findings/mark-immediate-dependents-stale!
+ (fn [_ _] (throw (ex-info "Simulated failure" {})))]
;; analyze-and-propagate! wraps in a transaction, so the upsert should be rolled back
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Simulated failure"
(#'deps.findings/analyze-and-propagate! card)))))
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/metadata_update_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/metadata_update_test.clj
index c9e467e458b..e310dbd4b1e 100644
--- a/enterprise/backend/test/metabase_enterprise/dependencies/metadata_update_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/metadata_update_test.clj
@@ -133,7 +133,7 @@
[:model/Card :id :result_metadata :card_schema]
:id [:in [parent-id child-id grandchild-id]])))
(t2/update! :model/Card parent-id {:dataset_query (lib/query mp orders)})
- (with-redefs [async/submit! (fn [f] (f))]
+ (mt/with-dynamic-fn-redefs [async/submit! (fn [f] (f))]
(events/publish-event! :event/card-update
{:object (assoc parent-card :dataset_query (lib/query mp orders))
:previous-object parent-card
@@ -158,7 +158,7 @@
:to_entity_type :card
:to_entity_id parent-id}]
(t2/update! :model/Card child-id {:result_metadata nil})
- (with-redefs [async/submit! (fn [f] (f))]
+ (mt/with-dynamic-fn-redefs [async/submit! (fn [f] (f))]
(events/publish-event! :event/card-update
{:object (assoc parent-card :dataset_query native-query)
:previous-object parent-card
@@ -194,7 +194,7 @@
[0 :display_name]
"new-name")]
(t2/update! :model/Card parent-id {:result_metadata new-result-metadata})
- (with-redefs [async/submit! (fn [f] (f))]
+ (mt/with-dynamic-fn-redefs [async/submit! (fn [f] (f))]
(events/publish-event! :event/card-update
{:object (assoc parent-card :result_metadata new-result-metadata)
:previous-object parent-card
@@ -237,7 +237,7 @@
(t2/update! :model/Card parent-id {:result_metadata new-parent-metadata})
(t2/update! :model/Card child-id {:result_metadata new-child-metadata})
(t2/update! :model/Card grandchild-id {:result_metadata new-grandchild-metadata})
- (with-redefs [async/submit! (fn [f] (f))]
+ (mt/with-dynamic-fn-redefs [async/submit! (fn [f] (f))]
(events/publish-event! :event/card-update
{:object (assoc parent-card :result_metadata new-parent-metadata)
:previous-object parent-card
@@ -279,7 +279,7 @@
(t2/update! :model/Card parent-id {:result_metadata new-parent-metadata})
(t2/update! :model/Card child-id {:result_metadata new-child-metadata})
(t2/update! :model/Card grandchild-id {:result_metadata nil})
- (with-redefs [async/submit! (fn [f] (f))]
+ (mt/with-dynamic-fn-redefs [async/submit! (fn [f] (f))]
(events/publish-event! :event/card-update
{:object (assoc parent-card :result_metadata new-parent-metadata)
:previous-object parent-card
@@ -391,14 +391,14 @@
:analyzed_entity_type :card
:analyzed_entity_id card-id)
db-deps-checked (atom [])
- original-deps-check @#'deps.events/synced-db->direct-dependents-of-changed-tables
+ original-deps-check (mt/original-fn #'deps.events/synced-db->direct-dependents-of-changed-tables)
table-before (into {} (t2/select-one :model/Table :id table-id))
filter-field-before (into {} (t2/select-one :model/Field :id filter-field-id))]
;; Re-sync the database, having made no changes to it.
- (with-redefs [deps.events/synced-db->direct-dependents-of-changed-tables
- (fn [db-id]
- (u/prog1 (original-deps-check db-id)
- (swap! db-deps-checked conj [db-id <>])))]
+ (mt/with-dynamic-fn-redefs [deps.events/synced-db->direct-dependents-of-changed-tables
+ (fn [db-id]
+ (u/prog1 (original-deps-check db-id)
+ (swap! db-deps-checked conj [db-id <>])))]
(sync/sync-database! (mt/db)))
(testing "sync doesn't update tables or fields that haven't changed"
(let [table-after (into {} (t2/select-one :model/Table :id table-id))
diff --git a/enterprise/backend/test/metabase_enterprise/email/api_test.clj b/enterprise/backend/test/metabase_enterprise/email/api_test.clj
index 0abde125f7e..b2171829277 100644
--- a/enterprise/backend/test/metabase_enterprise/email/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/email/api_test.clj
@@ -42,7 +42,7 @@
body default-email-override-settings]
(doseq [;; test what happens on both a successful and an unsuccessful connection.
[success? f] {true (fn [thunk]
- (with-redefs [email/test-smtp-settings (constantly {::email/error nil})]
+ (mt/with-dynamic-fn-redefs [email/test-smtp-settings (constantly {::email/error nil})]
(thunk)))
false (fn [thunk]
(with-redefs [email/retry-delay-ms 0]
@@ -75,12 +75,12 @@
(testing "Updating values with obfuscated password (#23919)"
(mt/with-temporary-setting-values [email-smtp-host-override "www.test.com"
email-smtp-password-override "preexisting"]
- (with-redefs [email/test-smtp-connection (fn [settings]
- (let [obfuscated? (str/starts-with? (:pass settings) "****")]
- (is (not obfuscated?) "We received an obfuscated password!")
- (if obfuscated?
- {::email/error (ex-info "Sent obfuscated password" {})}
- settings)))]
+ (mt/with-dynamic-fn-redefs [email/test-smtp-connection (fn [settings]
+ (let [obfuscated? (str/starts-with? (:pass settings) "****")]
+ (is (not obfuscated?) "We received an obfuscated password!")
+ (if obfuscated?
+ {::email/error (ex-info "Sent obfuscated password" {})}
+ settings)))]
(testing "If we don't change the password we don't see the password"
(let [payload (-> (email-override-settings)
;; user changes one property
@@ -107,7 +107,7 @@
(mt/with-premium-features [:cloud-custom-smtp]
(tu/discard-setting-changes [email-smtp-host-override email-smtp-port-override email-smtp-security-override
email-smtp-username-override email-smtp-password-override]
- (with-redefs [email/test-smtp-settings (constantly {::email/error nil})]
+ (mt/with-dynamic-fn-redefs [email/test-smtp-settings (constantly {::email/error nil})]
(is (= (-> default-email-override-settings
(assoc :with-corrections {})
(update :email-smtp-security-override name))
diff --git a/enterprise/backend/test/metabase_enterprise/harbormaster/client_test.clj b/enterprise/backend/test/metabase_enterprise/harbormaster/client_test.clj
index 25f76fc4b3f..a0198120609 100644
--- a/enterprise/backend/test/metabase_enterprise/harbormaster/client_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/harbormaster/client_test.clj
@@ -51,7 +51,7 @@
(testing "bearer-auth interceptor adds Authorization header with the api-key"
(let [api-key "test-api-key-123"
client (mock-client api-key)]
- (with-redefs [hm.client/client (constantly client)]
+ (mt/with-dynamic-fn-redefs [hm.client/client (constantly client)]
(mt/with-current-user (mt/user->id :rasta)
(let [req (hm.client/request :test-op)]
(is (= (str "Bearer " api-key)
@@ -63,7 +63,7 @@
;; Both requests use the same client, so any difference in the email header
;; proves it's read at request time.
(let [client (mock-client "test-key")]
- (with-redefs [hm.client/client (constantly client)]
+ (mt/with-dynamic-fn-redefs [hm.client/client (constantly client)]
(mt/with-current-user (mt/user->id :rasta)
(let [req (hm.client/request :test-op)]
diff --git a/enterprise/backend/test/metabase_enterprise/impersonation/driver_test.clj b/enterprise/backend/test/metabase_enterprise/impersonation/driver_test.clj
index e939a94eed3..34e41852250 100644
--- a/enterprise/backend/test/metabase_enterprise/impersonation/driver_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/impersonation/driver_test.clj
@@ -810,14 +810,14 @@
:tables
set)
default-table-set (tables-set)
- do-with-resolved-connection sql-jdbc.execute/do-with-resolved-connection]
- (with-redefs [sql-jdbc.execute/do-with-resolved-connection
- (fn [driver db options f]
- (do-with-resolved-connection driver db options
- (fn [conn]
- (when-not (:connection db)
- (driver/set-role! driver/*driver* conn role-a))
- (f conn))))]
+ do-with-resolved-connection (mt/original-fn #'sql-jdbc.execute/do-with-resolved-connection)]
+ (mt/with-dynamic-fn-redefs [sql-jdbc.execute/do-with-resolved-connection
+ (fn [driver db options f]
+ (do-with-resolved-connection driver db options
+ (fn [conn]
+ (when-not (:connection db)
+ (driver/set-role! driver/*driver* conn role-a))
+ (f conn))))]
(is (= default-table-set (tables-set)))))))))))))
(defn do-on-all-connection-in-pool [driver db-id options f]
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 829106d73c6..b519173a711 100644
--- a/enterprise/backend/test/metabase_enterprise/internal_stats/metabot_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/internal_stats/metabot_test.clj
@@ -276,7 +276,7 @@
;; openai is not currently in the metabase managed allow-list, but we still
;; want to test metering in case we ever enable these providers — bypass the
;; validator with `with-redefs` to set the provider directly.
- (with-redefs [metabot.settings/llm-metabot-provider (constantly "metabase/openai/gpt-4o")]
+ (mt/with-dynamic-fn-redefs [metabot.settings/llm-metabot-provider (constantly "metabase/openai/gpt-4o")]
(send-message! conv-id "Hello" "gpt-4o" 600 200)
(backdate-messages! conv-id yesterday))
(let [stats (sut/metabot-stats)]
@@ -297,16 +297,16 @@
;; openrouter/openai are not currently in the metabase managed allow-list,
;; but we still want to test metering in case we ever enable these providers
;; — bypass the validator with `with-redefs` to set the provider directly.
- (with-redefs [metabot.settings/llm-metabot-provider
- (constantly "metabase/openrouter/anthropic/claude-haiku-4-5")]
+ (mt/with-dynamic-fn-redefs [metabot.settings/llm-metabot-provider
+ (constantly "metabase/openrouter/anthropic/claude-haiku-4-5")]
(send-message! conv-1 "Q1" "anthropic/claude-haiku-4-5" 100 50)
(backdate-messages! conv-1 yesterday))
(mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider
"metabase/anthropic/claude-sonnet-4-6"]
(send-message! conv-2 "Q2" "claude-sonnet-4-6" 200 80)
(backdate-messages! conv-2 yesterday))
- (with-redefs [metabot.settings/llm-metabot-provider
- (constantly "metabase/openai/gpt-4o")]
+ (mt/with-dynamic-fn-redefs [metabot.settings/llm-metabot-provider
+ (constantly "metabase/openai/gpt-4o")]
(send-message! conv-3 "Q3" "gpt-4o" 300 120)
(backdate-messages! conv-3 yesterday))
(let [stats (sut/metabot-stats)]
diff --git a/enterprise/backend/test/metabase_enterprise/metabot_analytics/api_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_analytics/api_test.clj
index bdfe5be8c39..0a639ebde2b 100644
--- a/enterprise/backend/test/metabase_enterprise/metabot_analytics/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/metabot_analytics/api_test.clj
@@ -690,10 +690,10 @@
:slack-team-id "T123"
:slack-channel-id "C123"
:slack-thread-ts "1712785577.123456"})
- (with-redefs [slackbot.api/conversation-permalink (fn [channel ts]
- (is (= "C123" channel))
- (is (= "1712785577.123456" ts))
- permalink)]
+ (mt/with-dynamic-fn-redefs [slackbot.api/conversation-permalink (fn [channel ts]
+ (is (= "C123" channel))
+ (is (= "1712785577.123456" ts))
+ permalink)]
(let [response (mt/user-http-request :crowberto :get 200
(format "ee/metabot-analytics/conversations/%s" conversation-id))]
(is (= permalink (:slack_permalink response)))))
diff --git a/enterprise/backend/test/metabase_enterprise/metabot_analytics/queries_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_analytics/queries_test.clj
index 65a2bac39dc..01c8786d2eb 100644
--- a/enterprise/backend/test/metabase_enterprise/metabot_analytics/queries_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/metabot_analytics/queries_test.clj
@@ -2,7 +2,8 @@
(:require
[clojure.test :refer [are deftest is testing]]
[metabase-enterprise.metabot-analytics.queries :as analytics.queries]
- [metabase.metabot.tools :as metabot.tools]))
+ [metabase.metabot.tools :as metabot.tools]
+ [metabase.test :as mt]))
(set! *warn-on-reflection* true)
@@ -11,7 +12,7 @@
;; the API integration test.
(defn- with-stubbed-tables! [tables thunk]
- (with-redefs [analytics.queries/referenced-table-names (fn [_db _sql] tables)]
+ (mt/with-dynamic-fn-redefs [analytics.queries/referenced-table-names (fn [_db _sql] tables)]
(thunk)))
;;; ------------------------- happy paths -------------------------
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 5f9685cb4d1..067b412013c 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj
@@ -168,25 +168,25 @@
(deftest branches-endpoint-returns-branches-test
(testing "GET /api/ee/remote-sync/branches returns list of branches"
- (with-redefs [source/source-from-settings (constantly (mock-git-source :branches ["main" "develop" "feature-branch"]))]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly (mock-git-source :branches ["main" "develop" "feature-branch"]))]
(is (= {:items ["main" "develop" "feature-branch"]}
(mt/user-http-request :crowberto :get 200 "ee/remote-sync/branches"))))))
(deftest branches-endpoint-requires-superuser-test
(testing "GET /api/ee/remote-sync/branches requires superuser permissions"
- (with-redefs [source/source-from-settings (constantly (mock-git-source))]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly (mock-git-source))]
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :get 403 "ee/remote-sync/branches"))))))
(deftest branches-endpoint-errors-when-git-not-configured-test
(testing "GET /api/ee/remote-sync/branches errors when git source not configured"
- (with-redefs [source/source-from-settings (constantly nil)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly nil)]
(is (= "Source not configured. Please configure MB_GIT_SOURCE_REPO_URL environment variable."
(mt/user-http-request :crowberto :get 400 "ee/remote-sync/branches"))))))
(deftest branches-endpoint-handles-repository-errors-test
(testing "GET /api/ee/remote-sync/branches handles git repository errors"
- (with-redefs [source/source-from-settings (constantly (mock-git-source :error-on-branches? true))]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly (mock-git-source :error-on-branches? true))]
(is (= "Repository not found: Please check the repository URL"
(mt/user-http-request :crowberto :get 400 "ee/remote-sync/branches"))))))
@@ -198,7 +198,7 @@
(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"
remote-sync-token "test-token"
remote-sync-branch "main"]
- (with-redefs [source/source-from-settings (constantly mock-main)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly mock-main)]
(let [{:keys [task_id] :as resp} (mt/user-http-request :crowberto :post 200 "ee/remote-sync/import" {})
completed-task (wait-for-task-completion task_id)]
(is (=? {:status "success" :task_id int?} resp))
@@ -210,7 +210,7 @@
(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"
remote-sync-token "test-token"
remote-sync-branch "main"]
- (with-redefs [source/source-from-settings (constantly mock-develop)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly mock-develop)]
(let [{:as response :keys [task_id]} (mt/user-http-request :crowberto :post 200 "ee/remote-sync/import" {:branch "feature-branch"})
completed-task (wait-for-task-completion task_id)]
(is (= "success" (:status response)))
@@ -234,7 +234,7 @@
(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"
remote-sync-token "test-token"
remote-sync-branch "main"]
- (with-redefs [source/source-from-settings (constantly mock-main)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly mock-main)]
(let [{:as response :keys [task_id]} (mt/user-http-request :crowberto :post 200 "ee/remote-sync/import" {})
completed-task (wait-for-task-completion task_id)]
(is (= "success" (:status response)))
@@ -247,7 +247,7 @@
(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"
remote-sync-token "test-token"
remote-sync-branch "main"]
- (with-redefs [source/source-from-settings (constantly mock-source)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly mock-source)]
(is (= "Remote sync task in progress"
(mt/user-http-request :crowberto :post 400 "ee/remote-sync/import" {})))))))))
@@ -263,7 +263,7 @@
:model_collection_id 1
:status "updated"
:status_changed_at (java.time.OffsetDateTime/now)})
- (with-redefs [source/source-from-settings (constantly mock-main)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly mock-main)]
(is (= "There are unsaved changes in the Remote Sync collection which will be overwritten by the import. Force the import to discard these changes."
(:message (mt/user-http-request :crowberto :post 400 "ee/remote-sync/import" {}))))
(testing "But can force an import"
@@ -282,7 +282,7 @@
(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"
remote-sync-token "test-token"
remote-sync-branch "main"]
- (with-redefs [source/source-from-settings (constantly mock-source)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly mock-source)]
(is (= "Exports are only allowed when remote-sync-type is set to 'read-write'"
(mt/user-http-request :crowberto :post 400 "ee/remote-sync/export" {}))))))))))
@@ -294,7 +294,7 @@
(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"
remote-sync-token "test-token"
remote-sync-branch "main"]
- (with-redefs [source/source-from-settings (constantly mock-main)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly mock-main)]
(let [{:keys [task_id] :as resp} (mt/user-http-request :crowberto :post 200 "ee/remote-sync/export" {})
task (wait-for-task-completion task_id)]
(is (remote-sync.task/successful? task))
@@ -309,7 +309,7 @@
(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"
remote-sync-token "test-token"
remote-sync-branch "main"]
- (with-redefs [source/source-from-settings (constantly mock-main)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly mock-main)]
(let [{:keys [task_id] :as resp} (mt/user-http-request :crowberto :post 200 "ee/remote-sync/export"
{:branch "feature-branch" :message "Custom export message"})
task (wait-for-task-completion task_id)]
@@ -339,7 +339,7 @@
(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"
remote-sync-token "test-token"
remote-sync-branch "main"]
- (with-redefs [source/source-from-settings (constantly mock-main)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly mock-main)]
(let [response (mt/user-http-request :crowberto :post 200 "ee/remote-sync/export" {})
task (wait-for-task-completion (:task_id response))]
(is (remote-sync.task/failed? task))))))))))
@@ -352,7 +352,7 @@
(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"
remote-sync-token "test-token"
remote-sync-branch "main"]
- (with-redefs [source/source-from-settings (constantly mock-source)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly mock-source)]
(is (= "Remote sync task in progress"
(mt/user-http-request :crowberto :post 400 "ee/remote-sync/export" {}))))))))))
@@ -366,7 +366,7 @@
(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"
remote-sync-token "test-token"
remote-sync-branch "main"]
- (with-redefs [source/source-from-settings (constantly mock-source)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly mock-source)]
(is (= "Cannot export changes that will overwrite new changes in the branch."
(:message (mt/user-http-request :crowberto :post 400 "ee/remote-sync/export" {}))))
(testing "Can export when the versions match"
@@ -385,7 +385,7 @@
(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"
remote-sync-token "test-token"
remote-sync-branch "main"]
- (with-redefs [source/source-from-settings (constantly mock-source)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly mock-source)]
(testing "Can export with force"
(mt/user-http-request :crowberto :post 200 "ee/remote-sync/export" {:force true})))))))))
@@ -614,8 +614,8 @@
(deftest settings-update-succeeds-test
(testing "PUT /api/ee/remote-sync/settings successfully updates settings"
(let [mock-main (test-helpers/create-mock-source)]
- (with-redefs [settings/check-git-settings! (constantly nil)
- source/source-from-settings (constantly mock-main)]
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (constantly nil)
+ source/source-from-settings (constantly mock-main)]
(mt/with-temporary-setting-values [remote-sync-url nil
remote-sync-type :read-write]
(let [resp (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"
@@ -626,8 +626,8 @@
(deftest settings-update-triggers-import-in-read-only-test
(testing "PUT /api/ee/remote-sync/settings triggers import when type is read-only"
(let [mock-main (test-helpers/create-mock-source)]
- (with-redefs [settings/check-git-settings! (constantly nil)
- source/source-from-settings (constantly mock-main)]
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (constantly nil)
+ source/source-from-settings (constantly mock-main)]
(mt/with-temporary-setting-values [remote-sync-type :read-only
remote-sync-branch "main"
remote-sync-url "https://github.com/test/repo.git"
@@ -652,8 +652,8 @@
(deftest settings-cannot-change-with-dirty-data
(testing "PUT /api/ee/remote-sync/settings doesn't allow losing dirty data"
- (with-redefs [remote-sync.object/dirty? (constantly true)
- settings/check-and-update-remote-settings! #(throw (Exception. "Should not be called"))]
+ (mt/with-dynamic-fn-redefs [remote-sync.object/dirty? (constantly true)
+ settings/check-and-update-remote-settings! #(throw (Exception. "Should not be called"))]
(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"
remote-sync-token "test-token"
remote-sync-branch "main"
@@ -698,8 +698,8 @@
(testing "PUT /api/ee/remote-sync/settings with collections enables remote sync on a single collection"
(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! (constantly nil)
- impl/finish-remote-config! (constantly nil)]
+ (mt/with-dynamic-fn-redefs [settings/check-and-update-remote-settings! (constantly nil)
+ impl/finish-remote-config! (constantly nil)]
(let [response (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"
{:collections {coll-id true}})]
(is (= {:success true} response))
@@ -709,8 +709,8 @@
(testing "PUT /api/ee/remote-sync/settings with collections disables remote sync on a single collection"
(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 true}]
- (with-redefs [settings/check-and-update-remote-settings! (constantly nil)
- impl/finish-remote-config! (constantly nil)]
+ (mt/with-dynamic-fn-redefs [settings/check-and-update-remote-settings! (constantly nil)
+ impl/finish-remote-config! (constantly nil)]
(let [response (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"
{:collections {coll-id false}})]
(is (= {:success true} response))
@@ -721,8 +721,8 @@
(mt/with-temporary-setting-values [remote-sync-type :read-write]
(mt/with-temp [:model/Collection {coll1-id :id} {:name "Collection 1" :location "/" :is_remote_synced false}
:model/Collection {coll2-id :id} {:name "Collection 2" :location "/" :is_remote_synced false}]
- (with-redefs [settings/check-and-update-remote-settings! (constantly nil)
- impl/finish-remote-config! (constantly nil)]
+ (mt/with-dynamic-fn-redefs [settings/check-and-update-remote-settings! (constantly nil)
+ impl/finish-remote-config! (constantly nil)]
(let [response (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"
{:collections {coll1-id true coll2-id true}})]
(is (= {:success true} response))
@@ -734,8 +734,8 @@
(mt/with-temporary-setting-values [remote-sync-type :read-write]
(mt/with-temp [:model/Collection {coll1-id :id} {:name "Collection 1" :location "/" :is_remote_synced false}
:model/Collection {coll2-id :id} {:name "Collection 2" :location "/" :is_remote_synced true}]
- (with-redefs [settings/check-and-update-remote-settings! (constantly nil)
- impl/finish-remote-config! (constantly nil)]
+ (mt/with-dynamic-fn-redefs [settings/check-and-update-remote-settings! (constantly nil)
+ impl/finish-remote-config! (constantly nil)]
(let [response (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"
{:collections {coll1-id true coll2-id false}})]
(is (= {:success true} response))
@@ -748,8 +748,8 @@
(mt/with-temp [:model/Collection {parent-id :id} {:name "Parent" :location "/" :is_remote_synced false}
:model/Collection {child-id :id} {:name "Child" :location (format "/%d/" parent-id) :is_remote_synced false}
:model/Collection {grandchild-id :id} {:name "Grandchild" :location (format "/%d/%d/" parent-id child-id) :is_remote_synced false}]
- (with-redefs [settings/check-and-update-remote-settings! (constantly nil)
- impl/finish-remote-config! (constantly nil)]
+ (mt/with-dynamic-fn-redefs [settings/check-and-update-remote-settings! (constantly nil)
+ impl/finish-remote-config! (constantly nil)]
(let [response (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"
{:collections {parent-id true}})]
(is (= {:success true} response))
@@ -763,8 +763,8 @@
(mt/with-temp [:model/Collection {parent-id :id} {:name "Parent" :location "/" :is_remote_synced true}
:model/Collection {child-id :id} {:name "Child" :location (format "/%d/" parent-id) :is_remote_synced true}
:model/Collection {grandchild-id :id} {:name "Grandchild" :location (format "/%d/%d/" parent-id child-id) :is_remote_synced true}]
- (with-redefs [settings/check-and-update-remote-settings! (constantly nil)
- impl/finish-remote-config! (constantly nil)]
+ (mt/with-dynamic-fn-redefs [settings/check-and-update-remote-settings! (constantly nil)
+ impl/finish-remote-config! (constantly nil)]
(let [response (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"
{:collections {parent-id false}})]
(is (= {:success true} response))
@@ -785,8 +785,8 @@
:collection_id remote-synced-coll-id
:database_id (mt/id)
:dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}]
- (with-redefs [settings/check-and-update-remote-settings! (constantly nil)
- impl/finish-remote-config! (constantly nil)]
+ (mt/with-dynamic-fn-redefs [settings/check-and-update-remote-settings! (constantly nil)
+ impl/finish-remote-config! (constantly nil)]
(let [response (mt/user-http-request :crowberto :put 400 "ee/remote-sync/settings"
{:collections {remote-synced-coll-id true}})]
(is (= "Uses content that is not remote synced." (:error response)))))))))
@@ -804,8 +804,8 @@
:collection_id coll2-id
:database_id (mt/id)
:dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}]
- (with-redefs [settings/check-and-update-remote-settings! (constantly nil)
- impl/finish-remote-config! (constantly nil)]
+ (mt/with-dynamic-fn-redefs [settings/check-and-update-remote-settings! (constantly nil)
+ impl/finish-remote-config! (constantly nil)]
(let [response (mt/user-http-request :crowberto :put 400 "ee/remote-sync/settings"
{:collections {coll1-id false}})]
(is (= "Used by remote synced content." (:error response)))))))))
@@ -813,8 +813,8 @@
(deftest settings-collections-empty-is-no-op-test
(testing "PUT /api/ee/remote-sync/settings with empty collections is a no-op"
(mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :location "/" :is_remote_synced false}]
- (with-redefs [settings/check-and-update-remote-settings! (constantly nil)
- impl/finish-remote-config! (constantly nil)]
+ (mt/with-dynamic-fn-redefs [settings/check-and-update-remote-settings! (constantly nil)
+ impl/finish-remote-config! (constantly nil)]
(let [response (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"
{:collections {}})]
(is (= {:success true} response))
@@ -831,8 +831,8 @@
(testing "PUT /api/ee/remote-sync/settings rejects collection changes when remote-sync-type is read-only"
(mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :location "/" :is_remote_synced false}
:model/Collection {synced-coll-id :id} {:name "Synced Collection" :location "/" :is_remote_synced true}]
- (with-redefs [settings/check-and-update-remote-settings! (constantly nil)
- impl/finish-remote-config! (constantly nil)]
+ (mt/with-dynamic-fn-redefs [settings/check-and-update-remote-settings! (constantly nil)
+ impl/finish-remote-config! (constantly nil)]
(testing "rejects enabling collections when remote-sync-type is explicitly read-only"
(is (= "Cannot change synced collections when remote-sync-type is read-only."
(mt/user-http-request :crowberto :put 400 "ee/remote-sync/settings"
@@ -853,8 +853,8 @@
(testing "PUT /api/ee/remote-sync/settings skips read-only error when collections have no actual changes"
(mt/with-temp [:model/Collection {unsynced-id :id} {:name "Unsynced Collection" :location "/" :is_remote_synced false}
:model/Collection {synced-id :id} {:name "Synced Collection" :location "/" :is_remote_synced true}]
- (with-redefs [settings/check-and-update-remote-settings! (constantly nil)
- impl/finish-remote-config! (constantly nil)]
+ (mt/with-dynamic-fn-redefs [settings/check-and-update-remote-settings! (constantly nil)
+ impl/finish-remote-config! (constantly nil)]
(testing "sending false for already-unsynced collection in read-only mode succeeds"
(is (= {:success true}
(mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"
@@ -877,9 +877,9 @@
(mt/with-temp [:model/Collection {synced-id :id} {:name "Synced Collection" :location "/" :is_remote_synced true}
:model/Collection {unsynced-id :id} {:name "Unsynced Collection" :location "/" :is_remote_synced false}]
(let [bulk-set-called? (atom false)]
- (with-redefs [settings/check-and-update-remote-settings! (constantly nil)
- impl/finish-remote-config! (constantly nil)
- remote-sync.core/bulk-set-remote-sync (fn [& _] (reset! bulk-set-called? true))]
+ (mt/with-dynamic-fn-redefs [settings/check-and-update-remote-settings! (constantly nil)
+ impl/finish-remote-config! (constantly nil)
+ remote-sync.core/bulk-set-remote-sync (fn [& _] (reset! bulk-set-called? true))]
(testing "no-op collections do not call bulk-set-remote-sync"
(let [response (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"
{:collections {synced-id true unsynced-id false}})]
@@ -889,8 +889,8 @@
(deftest settings-collections-allows-changes-in-read-write-mode-test
(testing "PUT /api/ee/remote-sync/settings allows collection changes when remote-sync-type is 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! (constantly nil)
- impl/finish-remote-config! (constantly nil)]
+ (mt/with-dynamic-fn-redefs [settings/check-and-update-remote-settings! (constantly nil)
+ impl/finish-remote-config! (constantly nil)]
(testing "allows enabling collections when remote-sync-type is explicitly read-write"
(let [response (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"
{:remote-sync-type :read-write
@@ -917,7 +917,7 @@
remote-sync-token "test-token"
remote-sync-branch "main"
remote-sync-type :read-write]
- (with-redefs [source/source-from-settings (constantly mock-source)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly mock-source)]
(is (= {:status "success"
:message "Branch 'feature-branch' created from 'main'"}
(mt/user-http-request :crowberto :post 200 "ee/remote-sync/create-branch"
@@ -940,8 +940,8 @@
:model_collection_id 1
:status "updated"
:status_changed_at (java.time.OffsetDateTime/now)}]
- (with-redefs [source/source-from-settings (constantly mock-source)
- impl/async-export! (fn [_ _ _ & _opts] (assoc remote-sync :calls (swap! export-calls inc)))]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly mock-source)
+ impl/async-export! (fn [_ _ _ & _opts] (assoc remote-sync :calls (swap! export-calls inc)))]
(is (=? {:status "success"
:message "Stashing to feature-branch"}
(mt/user-http-request :crowberto :post 200 "ee/remote-sync/stash"
@@ -971,7 +971,7 @@
(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"
remote-sync-token "test-token"
remote-sync-branch "main"]
- (with-redefs [source/source-from-settings (constantly mock-source)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly mock-source)]
;; Clear cache before test
(impl/invalidate-remote-changes-cache!)
(let [response (mt/user-http-request :crowberto :get 200 "ee/remote-sync/has-remote-changes")]
@@ -989,7 +989,7 @@
(mt/with-temp [:model/RemoteSyncTask _ {:sync_task_type "import"
:ended_at :%now
:version "old-version"}]
- (with-redefs [source/source-from-settings (constantly mock-source)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly mock-source)]
;; Clear cache before test
(impl/invalidate-remote-changes-cache!)
(let [response (mt/user-http-request :crowberto :get 200 "ee/remote-sync/has-remote-changes")]
@@ -1007,7 +1007,7 @@
(mt/with-temp [:model/RemoteSyncTask _ {:sync_task_type "import"
:ended_at :%now
:version "mock-version"}]
- (with-redefs [source/source-from-settings (constantly mock-source)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly mock-source)]
;; Clear cache before test
(impl/invalidate-remote-changes-cache!)
(let [response (mt/user-http-request :crowberto :get 200 "ee/remote-sync/has-remote-changes")]
@@ -1027,9 +1027,9 @@
(mt/with-temp [:model/RemoteSyncTask _ {:sync_task_type "import"
:ended_at :%now
:version "mock-version"}]
- (with-redefs [source/source-from-settings (fn [& _args]
- (swap! call-count inc)
- mock-source)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (fn [& _args]
+ (swap! call-count inc)
+ mock-source)]
;; Clear cache before test
(impl/invalidate-remote-changes-cache!)
;; First call - should hit the source
@@ -1052,9 +1052,9 @@
(mt/with-temp [:model/RemoteSyncTask _ {:sync_task_type "import"
:ended_at :%now
:version "mock-version"}]
- (with-redefs [source/source-from-settings (fn [& _args]
- (swap! call-count inc)
- mock-source)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (fn [& _args]
+ (swap! call-count inc)
+ mock-source)]
;; Clear cache before test
(impl/invalidate-remote-changes-cache!)
;; First call - should hit the source
@@ -1077,9 +1077,9 @@
(mt/with-temp [:model/RemoteSyncTask _ {:sync_task_type "import"
:ended_at :%now
:version "mock-version"}]
- (with-redefs [source/source-from-settings (fn [& _args]
- (swap! call-count inc)
- mock-source)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (fn [& _args]
+ (swap! call-count inc)
+ mock-source)]
;; Clear cache before test
(impl/invalidate-remote-changes-cache!)
;; First call with main branch
@@ -1171,8 +1171,8 @@
(deftest settings-preserves-token-when-switching-to-read-only-test
(testing "PUT /api/ee/remote-sync/settings preserves token when switching from read-write to read-only"
(let [mock-source (test-helpers/create-mock-source)]
- (with-redefs [settings/check-git-settings! (constantly nil)
- source/source-from-settings (constantly mock-source)]
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (constantly nil)
+ source/source-from-settings (constantly mock-source)]
(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"
remote-sync-token "secret-token-value"
remote-sync-branch "main"
@@ -1188,8 +1188,8 @@
(deftest settings-preserves-token-when-changing-branch-test
(testing "PUT /api/ee/remote-sync/settings preserves token when changing branch"
(let [mock-source (test-helpers/create-mock-source)]
- (with-redefs [settings/check-git-settings! (constantly nil)
- source/source-from-settings (constantly mock-source)]
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (constantly nil)
+ source/source-from-settings (constantly mock-source)]
(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"
remote-sync-token "secret-token-value"
remote-sync-branch "main"
@@ -1205,8 +1205,8 @@
(deftest settings-clears-token-when-explicitly-nil-test
(testing "PUT /api/ee/remote-sync/settings clears token when explicitly set to nil"
(let [mock-source (test-helpers/create-mock-source)]
- (with-redefs [settings/check-git-settings! (constantly nil)
- source/source-from-settings (constantly mock-source)]
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (constantly nil)
+ source/source-from-settings (constantly mock-source)]
(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"
remote-sync-token "secret-token-value"
remote-sync-branch "main"
@@ -1223,8 +1223,8 @@
(deftest settings-updates-transforms-setting-test
(testing "PUT /api/ee/remote-sync/settings can update remote-sync-transforms setting"
(let [mock-source (test-helpers/create-mock-source)]
- (with-redefs [settings/check-git-settings! (constantly nil)
- source/source-from-settings (constantly mock-source)]
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (constantly nil)
+ source/source-from-settings (constantly mock-source)]
(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"
remote-sync-token "test-token"
remote-sync-branch "main"
@@ -1251,8 +1251,8 @@
(deftest settings-preserves-transforms-when-not-specified-test
(testing "PUT /api/ee/remote-sync/settings preserves transforms setting when not specified"
(let [mock-source (test-helpers/create-mock-source)]
- (with-redefs [settings/check-git-settings! (constantly nil)
- source/source-from-settings (constantly mock-source)]
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (constantly nil)
+ source/source-from-settings (constantly mock-source)]
(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"
remote-sync-token "test-token"
remote-sync-branch "main"
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 8b01b43814b..9eeb5fa7237 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj
@@ -279,9 +279,9 @@
(mt/with-temp [:model/Collection {_coll-id :id} {:name "Test Collection" :is_remote_synced true :entity_id "test-collection-1xxxx" :location "/"}]
(let [mock-source (test-helpers/create-mock-source)
progress-calls (atom [])]
- (with-redefs [remote-sync.task/update-progress!
- (fn [task-id progress]
- (swap! progress-calls conj {:task-id task-id :progress progress}))]
+ (mt/with-dynamic-fn-redefs [remote-sync.task/update-progress!
+ (fn [task-id progress]
+ (swap! progress-calls conj {:task-id task-id :progress progress}))]
(let [result (impl/import! (source.p/snapshot mock-source) task-id)]
(is (= :success (:status result)))
(is (= 5 (count @progress-calls)))
@@ -302,9 +302,9 @@
:model/Card _ {:collection_id coll-id}]
(let [mock-source (test-helpers/create-mock-source)
progress-calls (atom [])]
- (with-redefs [remote-sync.task/update-progress!
- (fn [task-id progress]
- (swap! progress-calls conj {:task-id task-id :progress progress}))]
+ (mt/with-dynamic-fn-redefs [remote-sync.task/update-progress!
+ (fn [task-id progress]
+ (swap! progress-calls conj {:task-id task-id :progress progress}))]
(let [result (impl/export! (source.p/snapshot mock-source) task-id "Test commit")]
(is (= :success (:status result)))
(is (pos? (count @progress-calls)))
@@ -483,8 +483,8 @@
(mt/with-temporary-setting-values [remote-sync-enabled true
remote-sync-url "https://github.com/test/repo.git"
remote-sync-branch ""]
- (with-redefs [source/source-from-settings (constantly mock-source)
- impl/async-import! (fn [& _args] (reset! import-started? true) 123)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly mock-source)
+ impl/async-import! (fn [& _args] (reset! import-started? true) 123)]
(impl/finish-remote-config!)
(is (= "main" (setting/get :remote-sync-branch))
"Should set branch to default branch")))))))
@@ -499,8 +499,8 @@
remote-sync-url "https://github.com/test/repo.git"
remote-sync-branch "main"
remote-sync-type :read-only]
- (with-redefs [source/source-from-settings (constantly mock-source)
- impl/async-import! (fn [& _args] (reset! import-called? true) {:id 123})]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly mock-source)
+ impl/async-import! (fn [& _args] (reset! import-called? true) {:id 123})]
(let [task-id (impl/finish-remote-config!)]
(is (= 123 task-id)
"Should return task ID from async-import!")
@@ -517,8 +517,8 @@
remote-sync-url "https://github.com/test/repo.git"
remote-sync-branch "main"
remote-sync-type :read-write]
- (with-redefs [source/source-from-settings (constantly mock-source)
- impl/async-import! (fn [& _args] (reset! import-called? true) 123)]
+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly mock-source)
+ impl/async-import! (fn [& _args] (reset! import-called? true) 123)]
(let [result (impl/finish-remote-config!)]
(is (nil? result)
"Should return nil when nothing is done")
@@ -532,7 +532,7 @@
(mt/with-temp [:model/Collection _ {:name "Remote Collection" :is_remote_synced true :location "/"}]
(mt/with-temporary-setting-values [remote-sync-url nil
remote-sync-enabled false]
- (with-redefs [collection/clear-remote-synced-collection! (fn [] (reset! clear-called? true))]
+ (mt/with-dynamic-fn-redefs [collection/clear-remote-synced-collection! (fn [] (reset! clear-called? true))]
(let [result (impl/finish-remote-config!)]
(is (nil? result)
"Should return nil when remote sync is disabled")
@@ -1243,7 +1243,7 @@ serdes/meta:
:type "library"
:entity_id collection/library-entity-id
:location "/"}]
- (with-redefs [remote-sync.task/last-version (constantly "previous-version")]
+ (mt/with-dynamic-fn-redefs [remote-sync.task/last-version (constantly "previous-version")]
(let [test-files {"main" {"collections/main/lib/lib.yaml"
(test-helpers/generate-collection-yaml collection/library-entity-id "Remote Library")}}
mock-source (test-helpers/create-mock-source :initial-files test-files)
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/models/remote_sync_object_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/models/remote_sync_object_test.clj
index 9dd82a73e50..2eb700ed3a0 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/models/remote_sync_object_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/models/remote_sync_object_test.clj
@@ -454,7 +454,7 @@
(deftest dirty-objects-all-model-types-including-new-test
(testing "dirty-objects handles all supported model types including Table, Field, and Segment"
;; Mock excluded-model-types to return empty set so all model types (including NativeQuerySnippet) are included
- (with-redefs [spec/excluded-model-types (constantly #{})]
+ (mt/with-dynamic-fn-redefs [spec/excluded-model-types (constantly #{})]
(mt/with-temp
[:model/Collection collection {:name "Test Collection"
:location "/"}
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 f9d682a5600..6b31ae68b6a 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/settings_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/settings_test.clj
@@ -17,10 +17,10 @@
:remote-sync-type :read-only
:remote-sync-branch "test-branch"
:remote-sync-token nil}]
- (with-redefs [settings/check-git-settings! (fn [{:keys [remote-sync-token]}]
- ;; git should always be checked with a nil or full token
- (is (or (nil? remote-sync-token) (#{full-token other-token} remote-sync-token)))
- true)]
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (fn [{:keys [remote-sync-token]}]
+ ;; git should always be checked with a nil or full token
+ (is (or (nil? remote-sync-token) (#{full-token other-token} remote-sync-token)))
+ true)]
(mt/with-temporary-setting-values [:remote-sync-token nil
:remote-sync-url nil
:remote-sync-type nil
@@ -48,9 +48,9 @@
(deftest check-and-update-remote-settings-partial-updates
(testing "Partial updates for non-git settings do not trigger git validation"
(let [git-check-called? (atom false)]
- (with-redefs [settings/check-git-settings! (fn [_]
- (reset! git-check-called? true)
- true)]
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (fn [_]
+ (reset! git-check-called? true)
+ true)]
(mt/with-temporary-setting-values [:remote-sync-transforms false
:remote-sync-auto-import false]
(testing "Updating only remote-sync-transforms does not check git settings"
@@ -72,9 +72,9 @@
(is (false? (settings/remote-sync-auto-import))))))))
(testing "Partial updates with git-related settings do trigger git validation"
(let [git-check-called? (atom false)]
- (with-redefs [settings/check-git-settings! (fn [_]
- (reset! git-check-called? true)
- true)]
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (fn [_]
+ (reset! git-check-called? true)
+ true)]
(mt/with-temporary-setting-values [:remote-sync-url "file://my/url.git"
:remote-sync-type :read-only
:remote-sync-branch "main"]
@@ -105,8 +105,8 @@
:remote-sync-branch "main"
:remote-sync-type :read-only}))))
(testing "Non-GitHub HTTPS URLs are accepted"
- (with-redefs [git/git-source (fn [& _] nil)
- git/branches (fn [_] ["main"])]
+ (mt/with-dynamic-fn-redefs [git/git-source (fn [& _] nil)
+ git/branches (fn [_] ["main"])]
(is (nil? (settings/check-git-settings! {:remote-sync-url "https://gitlab.com/foo/bar.git"
:remote-sync-token nil
:remote-sync-branch "main"
diff --git a/enterprise/backend/test/metabase_enterprise/replacement/execute_test.clj b/enterprise/backend/test/metabase_enterprise/replacement/execute_test.clj
index 8f0dc622c01..d56e7b1d303 100644
--- a/enterprise/backend/test/metabase_enterprise/replacement/execute_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/replacement/execute_test.clj
@@ -17,9 +17,9 @@
(mt/with-model-cleanup [:model/ReplacementRun]
(let [writes (atom [])
done? (promise)]
- (with-redefs [replacement-run/update-progress!
- (fn [_run-id progress]
- (swap! writes conj progress))]
+ (mt/with-dynamic-fn-redefs [replacement-run/update-progress!
+ (fn [_run-id progress]
+ (swap! writes conj progress))]
(let [record (replacement-run/create-run! :card 1 :card 2 (mt/user->id :rasta))
progress (replacement-run/run-row->progress record done?)]
(replacement.execute/execute-async!
@@ -43,9 +43,9 @@
(mt/with-model-cleanup [:model/ReplacementRun]
(let [writes (atom [])
done? (promise)]
- (with-redefs [replacement-run/update-progress!
- (fn [_run-id progress]
- (swap! writes conj progress))]
+ (mt/with-dynamic-fn-redefs [replacement-run/update-progress!
+ (fn [_run-id progress]
+ (swap! writes conj progress))]
(let [record (replacement-run/create-run! :card 1 :card 2 (mt/user->id :rasta))
progress (replacement-run/run-row->progress record done?)]
(replacement.execute/execute-async!
@@ -72,9 +72,9 @@
done? (promise)
pause (promise)
ready (promise)]
- (with-redefs [replacement-run/update-progress!
- (fn [_run-id progress]
- (swap! writes conj progress))]
+ (mt/with-dynamic-fn-redefs [replacement-run/update-progress!
+ (fn [_run-id progress]
+ (swap! writes conj progress))]
(let [record (replacement-run/create-run! :card 1 :card 2 (mt/user->id :rasta))
progress (replacement-run/run-row->progress record done?)]
(replacement.execute/execute-async!
diff --git a/enterprise/backend/test/metabase_enterprise/replacement/runner_test.clj b/enterprise/backend/test/metabase_enterprise/replacement/runner_test.clj
index ad851ffc412..8a290ad316a 100644
--- a/enterprise/backend/test/metabase_enterprise/replacement/runner_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/replacement/runner_test.clj
@@ -248,12 +248,12 @@
(doseq [card [old-card child-1 child-2]]
(events/publish-event! :event/card-create {:object card :user-id (mt/user->id :rasta)}))
(deps.test/synchronously-run-backfill!)
- (let [original-swap! replacement.source-swap/swap-source!]
- (with-redefs [replacement.source-swap/swap-source!
- (fn [entity object old-source new-source]
- (if (= (second entity) child-1-id)
- (throw (ex-info "Simulated swap failure" {:entity entity}))
- (original-swap! entity object old-source new-source)))]
+ (let [original-swap! (mt/original-fn #'replacement.source-swap/swap-source!)]
+ (mt/with-dynamic-fn-redefs [replacement.source-swap/swap-source!
+ (fn [entity object old-source new-source]
+ (if (= (second entity) child-1-id)
+ (throw (ex-info "Simulated swap failure" {:entity entity}))
+ (original-swap! entity object old-source new-source)))]
(let [ex (is (thrown-with-msg? clojure.lang.ExceptionInfo #"1 of 2 entities failed"
(replacement.runner/run-swap-source!
[:card old-id] [:card new-id])))]
diff --git a/enterprise/backend/test/metabase_enterprise/replacement/source_check_test.clj b/enterprise/backend/test/metabase_enterprise/replacement/source_check_test.clj
index 50ce06596cb..9af9f2d0ce1 100644
--- a/enterprise/backend/test/metabase_enterprise/replacement/source_check_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/replacement/source_check_test.clj
@@ -55,8 +55,8 @@
:model/Table {t2-id :id} {:db_id db-id}
:model/Field _ {:table_id t1-id :name "id" :base_type :type/Integer}
:model/Field _ {:table_id t2-id :name "id" :base_type :type/Integer}]
- (with-redefs [replacement.usages/transitive-usages
- (constantly [[:table t2-id]])]
+ (mt/with-dynamic-fn-redefs [replacement.usages/transitive-usages
+ (constantly [[:table t2-id]])]
(let [result (replacement.source-check/check-replace-source
[:table t1-id] [:table t2-id])]
(is (false? (:success result)))
@@ -283,8 +283,8 @@
;; FK from t3 to t1 triggers implicit-joins
:model/Field _ {:table_id t3-id :name "t1_fk" :base_type :type/Integer
:semantic_type :type/FK :fk_target_field_id f1-id}]
- (with-redefs [replacement.usages/transitive-usages
- (constantly [[:table t2-id]])]
+ (mt/with-dynamic-fn-redefs [replacement.usages/transitive-usages
+ (constantly [[:table t2-id]])]
(let [result (replacement.source-check/check-replace-source
[:table t1-id] [:table t2-id])]
(is (false? (:success result)))
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/api/dashboard_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/api/dashboard_test.clj
index 505732c325b..c4c9ee3d163 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/api/dashboard_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/api/dashboard_test.clj
@@ -20,7 +20,7 @@
(field-values/get-or-create-full-field-values! (t2/select-one :model/Field :id (mt/id :categories :name)))
(mt/with-temp-vals-in-db :model/FieldValues (u/the-id (t2/select-one-pk :model/FieldValues :field_id (mt/id :categories :name))) {:values ["Good" "Bad"]}
(api.dashboard-test/with-chain-filter-fixtures [{:keys [dashboard]}]
- (with-redefs [metabase.parameters.chain-filter/use-cached-field-values? (constantly false)]
+ (mt/with-dynamic-fn-redefs [metabase.parameters.chain-filter/use-cached-field-values? (constantly false)]
(testing "GET /api/dashboard/:id/params/:param-key/values"
(mt/let-url [url (api.dashboard-test/chain-filter-values-url dashboard "_CATEGORY_NAME_")]
(is (= {:values [["African"] ["American"]]
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/api/field_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/api/field_test.clj
index afe72a94814..e88776c8189 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/api/field_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/api/field_test.clj
@@ -148,7 +148,7 @@
;; Warm up the cache
(mt/user-http-request :rasta :get 200 (str "field/" (:id field) "/values"))
(testing "Do we use cached values when available?"
- (with-redefs [field-values/distinct-values (fn [_] (assert false "Should not be called"))]
+ (mt/with-dynamic-fn-redefs [field-values/distinct-values (fn [_] (assert false "Should not be called"))]
(is (some? (:values (mt/user-http-request :rasta :get 200 (str "field/" (:id field) "/values")))))
(is (= 1 (t2/count :model/FieldValues
:field_id (:id field)
@@ -174,8 +174,8 @@
(is (some? fv-id)))
(t2/update! :model/FieldValues fv-id
{:values new-values})
- (with-redefs [field-values/distinct-values (constantly {:values (map vector new-values)
- :has_more_values false})]
+ (mt/with-dynamic-fn-redefs [field-values/distinct-values (constantly {:values (map vector new-values)
+ :has_more_values false})]
(is (= (map vector new-values)
(:values (mt/user-http-request :rasta :get 200 (str "field/" (:id field) "/values")))))))
(finally
@@ -186,8 +186,8 @@
;; make sure we have a cache
(mt/user-http-request :rasta :get 200 (str "field/" (:id field) "/values"))
(let [old-sandbox-fv-id (t2/select-one-pk :model/FieldValues :field_id (:id field) :type :advanced)]
- (with-redefs [field-values/advanced-field-values-expired? (fn [fv]
- (= (:id fv) old-sandbox-fv-id))]
+ (mt/with-dynamic-fn-redefs [field-values/advanced-field-values-expired? (fn [fv]
+ (= (:id fv) old-sandbox-fv-id))]
(mt/user-http-request :rasta :get 200 (str "field/" (:id field) "/values"))
;; did the old one get deleted?
(is (not (t2/exists? :model/FieldValues :id old-sandbox-fv-id)))
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/api/gtap_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/api/gtap_test.clj
index 09c6e044451..a2aa4fa2784 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/api/gtap_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/api/gtap_test.clj
@@ -152,7 +152,7 @@
:card_id card-id
:attribute_remappings {"foo" 1}}))))))
(testing "A database without the saved question sandboxing features returns a 400 error"
- (with-redefs [driver.util/supports? (fn [_ feature _] (not= feature :saved-question-sandboxing))]
+ (mt/with-dynamic-fn-redefs [driver.util/supports? (fn [_ feature _] (not= feature :saved-question-sandboxing))]
(mt/with-temp [:model/Card {card-id :id}]
(with-gtap-cleanup!
(is (=? {:message "Sandboxing with a saved question is not enabled for this database."}
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/models/params/field_values_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/models/params/field_values_test.clj
index f6abb7169d1..ba04715f513 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/models/params/field_values_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/models/params/field_values_test.clj
@@ -88,7 +88,7 @@
(mt/with-premium-features #{:sandboxes}
(testing "gtap with card and remappings"
;; hack so that we don't have to setup all the sandbox permissions the table
- (with-redefs [ee-params.field-values/field-is-sandboxed? (constantly true)]
+ (mt/with-dynamic-fn-redefs [ee-params.field-values/field-is-sandboxed? (constantly true)]
(let [field (t2/select-one :model/Field (mt/id :categories :name))
hash-input-for-user-id-with-attributes (fn [user-id login-attributes field]
(mt/with-temp-vals-in-db :model/User user-id {:login_attributes login-attributes}
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/pulse_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/pulse_test.clj
index 84e7c86febd..12741036991 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/pulse_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/pulse_test.clj
@@ -58,7 +58,7 @@
:user_id (mt/user->id :rasta)}]
(mt/with-temporary-setting-values [email-from-address "[email protected]"]
(mt/with-fake-inbox
- (with-redefs [notification.send/channel-send-retrying! (fn [_ _ _ _] :noop)]
+ (mt/with-dynamic-fn-redefs [notification.send/channel-send-retrying! (fn [_ _ _ _] :noop)]
(mt/with-test-user :lucky
(pulse.send/send-pulse! pulse)))
(is (= {:topic :subscription-send
@@ -182,7 +182,7 @@
recipients (-> pulse :channels first :recipients)]
(sort (map :id recipients))))]
(mt/with-test-user :rasta
- (with-redefs [perms-util/sandboxed-or-impersonated-user? (constantly false)]
+ (mt/with-dynamic-fn-redefs [perms-util/sandboxed-or-impersonated-user? (constantly false)]
(is (= (sort [(mt/user->id :rasta) (mt/user->id :crowberto)])
(-> (mt/user-http-request :rasta :get 200 "pulse/")
recipient-ids)))
@@ -190,7 +190,7 @@
(-> (mt/user-http-request :rasta :get 200 (format "pulse/%d" pulse-id))
vector
recipient-ids))))
- (with-redefs [perms-util/sandboxed-or-impersonated-user? (constantly true)]
+ (mt/with-dynamic-fn-redefs [perms-util/sandboxed-or-impersonated-user? (constantly true)]
(is (= [(mt/user->id :rasta)]
(-> (mt/user-http-request :rasta :get 200 "pulse/")
recipient-ids)))
@@ -210,14 +210,14 @@
:model/PulseChannelRecipient _ {:pulse_channel_id pc-id :user_id (mt/user->id :crowberto)}
:model/PulseChannelRecipient _ {:pulse_channel_id pc-id :user_id (mt/user->id :rasta)}]
(mt/with-test-user :rasta
- (with-redefs [perms-util/sandboxed-or-impersonated-user? (constantly true)]
+ (mt/with-dynamic-fn-redefs [perms-util/sandboxed-or-impersonated-user? (constantly true)]
;; Rasta, a sandboxed user, updates the pulse, but does not include Crowberto in the recipients list
(mt/user-http-request :rasta :put 200 (format "pulse/%d" pulse-id)
{:channels [(assoc pc :recipients [{:id (mt/user->id :rasta)}])]}))
;; Check that both Rasta and Crowberto are still recipients
(is (= (sort [(mt/user->id :rasta) (mt/user->id :crowberto)])
(->> (#'api.pulse/email-channel (models.pulse/retrieve-alert pulse-id)) :recipients (map :id) sort)))
- (with-redefs [perms-util/sandboxed-or-impersonated-user? (constantly false)]
+ (mt/with-dynamic-fn-redefs [perms-util/sandboxed-or-impersonated-user? (constantly false)]
;; Rasta, a non-sandboxed user, updates the pulse, but does not include Crowberto in the recipients list
(mt/user-http-request :rasta :put 200 (format "pulse/%d" pulse-id)
{:channels [(assoc pc :recipients [{:id (mt/user->id :rasta)}])]})
diff --git a/enterprise/backend/test/metabase_enterprise/scim/v2/api_test.clj b/enterprise/backend/test/metabase_enterprise/scim/v2/api_test.clj
index ea22af1e824..8389ef9d5fe 100644
--- a/enterprise/backend/test/metabase_enterprise/scim/v2/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/scim/v2/api_test.clj
@@ -77,7 +77,7 @@
(is (== 1 (mt/metric-value system :metabase-scim/response-ok)))
(is (== 1 (mt/metric-value system :metabase-scim/response-error))))
(testing "Unexpected server error (500)"
- (with-redefs [scim-api/scim-response #(throw (Exception.))]
+ (mt/with-dynamic-fn-redefs [scim-api/scim-response #(throw (Exception.))]
(scim-client :get 500 "ee/scim/v2/Users")
(is (== 1 (mt/metric-value system :metabase-scim/response-ok)))
(is (== 2 (mt/metric-value system :metabase-scim/response-error)))))))))
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 8334dbd1251..c677f6ad298 100644
--- a/enterprise/backend/test/metabase_enterprise/security_center/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/security_center/api_test.clj
@@ -72,7 +72,7 @@
(deftest trial-subscription-gate-test
(testing "Security Center is not available on trial subscriptions"
(mt/with-premium-features #{:admin-security-center}
- (with-redefs [token-check/is-trial? (constantly true)]
+ (mt/with-dynamic-fn-redefs [token-check/is-trial? (constantly true)]
(testing "GET /api/ee/security-center returns 402 for trial"
(is (=? {:message "Security Center is not available on this instance."
:status "error-premium-feature-not-available"}
@@ -183,13 +183,13 @@
(testing "non-superuser gets 403"
(mt/user-http-request :rasta :post 403 "ee/security-center/test-notification"))
(testing "superuser can send test notification with no body — falls back to saved settings"
- (with-redefs [notification/send-test-notification! (constantly nil)]
+ (mt/with-dynamic-fn-redefs [notification/send-test-notification! (constantly nil)]
(is (= {:success true}
(mt/user-http-request :crowberto :post 200 "ee/security-center/test-notification")))))
(testing "returns 400 when no channels are configured"
- (with-redefs [notification/send-test-notification!
- (fn [_] (throw (ex-info "No notification channels are configured."
- {:status-code 400})))]
+ (mt/with-dynamic-fn-redefs [notification/send-test-notification!
+ (fn [_] (throw (ex-info "No notification channels are configured."
+ {:status-code 400})))]
(mt/user-http-request :crowberto :post 400 "ee/security-center/test-notification"))))))
(deftest test-notification-uses-body-test
diff --git a/enterprise/backend/test/metabase_enterprise/security_center/fetch_test.clj b/enterprise/backend/test/metabase_enterprise/security_center/fetch_test.clj
index 2c1dda8c0fb..e676fe8c75b 100644
--- a/enterprise/backend/test/metabase_enterprise/security_center/fetch_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/security_center/fetch_test.clj
@@ -27,7 +27,7 @@
(deftest sync-advisories-inserts-new-test
(mt/with-model-cleanup [:model/SecurityAdvisory]
- (with-redefs [fetch/fetch-advisories-from-store (constantly [(make-advisory "SC-FETCH-001")])]
+ (mt/with-dynamic-fn-redefs [fetch/fetch-advisories-from-store (constantly [(make-advisory "SC-FETCH-001")])]
(fetch/sync-advisories!)
(let [row (t2/select-one :model/SecurityAdvisory :advisory_id "SC-FETCH-001")]
(is (some? row))
@@ -40,8 +40,8 @@
(mt/with-temp [:model/SecurityAdvisory _existing
(make-advisory "SC-FETCH-002" :severity "low" :title "Old title" :match_status "active"
:published_at #t "2026-03-24T00:00:00Z" :updated_at #t "2026-03-24T00:00:00Z")]
- (with-redefs [fetch/fetch-advisories-from-store
- (constantly [(make-advisory "SC-FETCH-002" :title "New title" :severity "critical")])]
+ (mt/with-dynamic-fn-redefs [fetch/fetch-advisories-from-store
+ (constantly [(make-advisory "SC-FETCH-002" :title "New title" :severity "critical")])]
(fetch/sync-advisories!)
(is (=? {:title "New title"
:severity :critical
@@ -57,8 +57,8 @@
:updated_at #t "2026-03-24T00:00:00Z"
:acknowledged_by user-id
:acknowledged_at #t "2026-03-25T00:00:00Z")]
- (with-redefs [fetch/fetch-advisories-from-store
- (constantly [(make-advisory "SC-FETCH-003" :title "Updated title")])]
+ (mt/with-dynamic-fn-redefs [fetch/fetch-advisories-from-store
+ (constantly [(make-advisory "SC-FETCH-003" :title "Updated title")])]
(fetch/sync-advisories!)
(is (=? {:title "Updated title"
:acknowledged_by some?
@@ -108,8 +108,8 @@
(deftest sync-advisories-stores-updated-at-test
(mt/with-model-cleanup [:model/SecurityAdvisory]
- (with-redefs [fetch/fetch-advisories-from-store
- (constantly [(make-advisory "SC-UPD-001" :updated_at #t "2026-04-01T12:00:00Z")])]
+ (mt/with-dynamic-fn-redefs [fetch/fetch-advisories-from-store
+ (constantly [(make-advisory "SC-UPD-001" :updated_at #t "2026-04-01T12:00:00Z")])]
(fetch/sync-advisories!)
(let [row (t2/select-one :model/SecurityAdvisory :advisory_id "SC-UPD-001")]
(is (some? (:updated_at row)))
@@ -119,8 +119,8 @@
(testing "updated_at is refreshed when an existing advisory is re-synced"
(mt/with-temp [:model/SecurityAdvisory _
(make-advisory "SC-UPD-003" :match_status "unknown" :published_at #t "2026-03-24T00:00:00Z" :updated_at #t "2026-03-24T00:00:00Z")]
- (with-redefs [fetch/fetch-advisories-from-store
- (constantly [(make-advisory "SC-UPD-003" :updated_at #t "2026-04-02T08:00:00Z")])]
+ (mt/with-dynamic-fn-redefs [fetch/fetch-advisories-from-store
+ (constantly [(make-advisory "SC-UPD-003" :updated_at #t "2026-04-02T08:00:00Z")])]
(fetch/sync-advisories!)
(is (=? {:updated_at some?}
(t2/select-one :model/SecurityAdvisory :advisory_id "SC-UPD-003")))
@@ -164,15 +164,15 @@
(deftest sync-advisories-handles-fetch-error-test
(testing "network error doesn't throw"
- (with-redefs [fetch/fetch-advisories-from-store (fn [] (throw (Exception. "connection refused")))]
+ (mt/with-dynamic-fn-redefs [fetch/fetch-advisories-from-store (fn [] (throw (Exception. "connection refused")))]
(is (nil? (fetch/sync-advisories!))))))
(deftest sync-advisories-handles-upsert-error-test
(testing "error on one advisory doesn't block others"
(mt/with-model-cleanup [:model/SecurityAdvisory]
- (with-redefs [fetch/fetch-advisories-from-store
- (constantly [(make-advisory "SC-FETCH-BAD" :severity "not-a-valid-severity!!!")
- (make-advisory "SC-FETCH-GOOD")])]
+ (mt/with-dynamic-fn-redefs [fetch/fetch-advisories-from-store
+ (constantly [(make-advisory "SC-FETCH-BAD" :severity "not-a-valid-severity!!!")
+ (make-advisory "SC-FETCH-GOOD")])]
(fetch/sync-advisories!)
(testing "good advisory was still inserted"
(is (some? (t2/select-one :model/SecurityAdvisory :advisory_id "SC-FETCH-GOOD"))))))))
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 9f18d56e3b7..dfa2a5b2fa0 100644
--- a/enterprise/backend/test/metabase_enterprise/security_center/notification_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/security_center/notification_test.clj
@@ -66,7 +66,7 @@
:severity "critical"
:match_status "active"
:last_notified_at (t/minus (t/offset-date-time) (t/hours 25))})]
- (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (mt/with-dynamic-fn-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
(task.sync/send-repeat-notifications!)
(is (= ["SC-REPEAT-001"] @notified))))))
@@ -77,7 +77,7 @@
:severity "critical"
:match_status "active"
:last_notified_at (t/minus (t/offset-date-time) (t/hours 12))})]
- (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (mt/with-dynamic-fn-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
(task.sync/send-repeat-notifications!)
(is (empty? @notified))))))
@@ -88,7 +88,7 @@
:severity "high"
:match_status "active"
:last_notified_at (t/minus (t/offset-date-time) (t/days 8))})]
- (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (mt/with-dynamic-fn-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
(task.sync/send-repeat-notifications!)
(is (= ["SC-REPEAT-003"] @notified))))))
@@ -99,7 +99,7 @@
:severity "high"
:match_status "active"
:last_notified_at (t/minus (t/offset-date-time) (t/days 1))})]
- (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (mt/with-dynamic-fn-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
(task.sync/send-repeat-notifications!)
(is (empty? @notified))))))
@@ -110,7 +110,7 @@
:severity "low"
:match_status "active"
:last_notified_at nil})]
- (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (mt/with-dynamic-fn-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
(task.sync/send-repeat-notifications!)
(is (= ["SC-REPEAT-005"] @notified))))))
@@ -121,7 +121,7 @@
:severity "medium"
:match_status "active"
:last_notified_at (t/minus (t/offset-date-time) (t/days 8))})]
- (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (mt/with-dynamic-fn-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
(task.sync/send-repeat-notifications!)
(is (= ["SC-MED-001"] @notified))))))
@@ -132,7 +132,7 @@
:severity "low"
:match_status "active"
:last_notified_at (t/minus (t/offset-date-time) (t/days 5))})]
- (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (mt/with-dynamic-fn-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
(task.sync/send-repeat-notifications!)
(is (empty? @notified))))))
@@ -143,7 +143,7 @@
:severity "high"
:match_status "error"
:last_notified_at nil})]
- (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (mt/with-dynamic-fn-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
(task.sync/send-repeat-notifications!)
(is (= ["SC-ERR-001"] @notified)))))))))
@@ -160,7 +160,7 @@
:last_notified_at nil
:acknowledged_by user-id
:acknowledged_at (mi/now)})]
- (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (mt/with-dynamic-fn-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
(task.sync/send-repeat-notifications!)
(is (empty? @notified))))))
@@ -171,7 +171,7 @@
:severity "critical"
:match_status "not_affected"
:last_notified_at nil})]
- (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (mt/with-dynamic-fn-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
(task.sync/send-repeat-notifications!)
(is (empty? @notified))))))
@@ -182,7 +182,7 @@
:severity "critical"
:match_status "resolved"
:last_notified_at nil})]
- (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (mt/with-dynamic-fn-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
(task.sync/send-repeat-notifications!)
(is (empty? @notified)))))))))
@@ -202,11 +202,11 @@
:severity "critical"
:match_status "active"
:last_notified_at nil})]
- (with-redefs [notification/notify-advisory! (fn [a]
- (swap! call-count inc)
- (if (= 1 @call-count)
- (throw (ex-info "transient failure" {}))
- (swap! notified conj (:advisory_id a))))]
+ (mt/with-dynamic-fn-redefs [notification/notify-advisory! (fn [a]
+ (swap! call-count inc)
+ (if (= 1 @call-count)
+ (throw (ex-info "transient failure" {}))
+ (swap! notified conj (:advisory_id a))))]
(task.sync/send-repeat-notifications!)
;; The second advisory should still be notified despite the first one failing
(is (= 1 (count @notified))))))))))
@@ -265,7 +265,7 @@
:severity "critical"
:match_status "active"})]
(mt/with-temporary-setting-values [admin-email "[email protected]"]
- (with-redefs [settings/security-center-email-recipients (constantly recips)]
+ (mt/with-dynamic-fn-redefs [settings/security-center-email-recipients (constantly recips)]
(with-send-redef (fn [notif & _] (reset! sent notif))
(notification/notify-advisory! advisory)
(let [email-handler (first (filter #(= :channel/email (:channel_type %)) (:handlers @sent)))
@@ -283,7 +283,7 @@
:severity "high"
:match_status "active"})]
(mt/with-temporary-setting-values [admin-email nil]
- (with-redefs [settings/security-center-email-recipients (constantly recips)]
+ (mt/with-dynamic-fn-redefs [settings/security-center-email-recipients (constantly recips)]
(with-send-redef (fn [notif & _] (reset! sent notif))
(notification/notify-advisory! advisory)
(let [email-handler (first (filter #(= :channel/email (:channel_type %)) (:handlers @sent)))
@@ -299,7 +299,7 @@
:severity "critical"
:match_status "active"})]
(mt/with-temporary-setting-values [admin-email "[email protected]"]
- (with-redefs [settings/security-center-email-recipients (constantly recips)]
+ (mt/with-dynamic-fn-redefs [settings/security-center-email-recipients (constantly recips)]
(with-send-redef (fn [notif & _] (reset! sent notif))
(notification/notify-advisory! advisory)
(let [email-handler (first (filter #(= :channel/email (:channel_type %)) (:handlers @sent)))
@@ -317,7 +317,7 @@
:severity "high"
:match_status "active"})]
(mt/with-temporary-setting-values [admin-email nil]
- (with-redefs [settings/security-center-email-recipients (constantly custom-recip)]
+ (mt/with-dynamic-fn-redefs [settings/security-center-email-recipients (constantly custom-recip)]
(with-send-redef (fn [notif & _] (reset! sent notif))
(notification/notify-advisory! advisory)
(let [email-handler (first (filter #(= :channel/email (:channel_type %)) (:handlers @sent)))]
@@ -333,7 +333,7 @@
:severity "critical"
:match_status "active"})]
(mt/with-temporary-setting-values [slack-token-valid? true]
- (with-redefs [settings/security-center-slack-channel (constantly "#security-alerts")]
+ (mt/with-dynamic-fn-redefs [settings/security-center-slack-channel (constantly "#security-alerts")]
(with-send-redef (fn [notif & _] (reset! sent notif))
(notification/notify-advisory! advisory)
(let [slack-handler (first (filter #(= :channel/slack (:channel_type %)) (:handlers @sent)))]
@@ -348,7 +348,7 @@
(advisory-fixture {:advisory_id "SC-SLACK-002"
:severity "low"
:match_status "active"})]
- (with-redefs [settings/security-center-slack-channel (constantly nil)]
+ (mt/with-dynamic-fn-redefs [settings/security-center-slack-channel (constantly nil)]
(with-send-redef (fn [notif & _] (reset! sent notif))
(notification/notify-advisory! advisory)
(is (empty? (filter #(= :channel/slack (:channel_type %)) (:handlers @sent))))))))))
@@ -361,7 +361,7 @@
:severity "medium"
:match_status "active"})]
(mt/with-temporary-setting-values [slack-token-valid? false]
- (with-redefs [settings/security-center-slack-channel (constantly "#alerts")]
+ (mt/with-dynamic-fn-redefs [settings/security-center-slack-channel (constantly "#alerts")]
(with-send-redef (fn [notif & _] (reset! sent notif))
(notification/notify-advisory! advisory)
(is (empty? (filter #(= :channel/slack (:channel_type %)) (:handlers @sent)))))))))))
@@ -415,7 +415,7 @@
(deftest send-test-notification-throws-when-no-channels-test
(testing "send-test-notification! throws when no channels are configured"
- (with-redefs [channel.settings/email-configured? (constantly false)]
+ (mt/with-dynamic-fn-redefs [channel.settings/email-configured? (constantly false)]
(is (thrown-with-msg? Exception #"No notification channels are configured"
(notification/send-test-notification! {:email-recipients nil
:slack-channel nil}))))))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/api_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/api_test.clj
index 56a0027bd85..0863f72e177 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/api_test.clj
@@ -18,9 +18,9 @@
(mt/with-premium-features #{:semantic-search}
(semantic.tu/with-test-db! {:mode :mock-initialized}
(with-open [index-ref (semantic.tu/open-temp-index!)]
- (with-redefs [semantic.index-metadata/get-active-index-state (fn [_ _]
- {:index @index-ref
- :status :active})]
+ (mt/with-dynamic-fn-redefs [semantic.index-metadata/get-active-index-state (fn [_ _]
+ {:index @index-ref
+ :status :active})]
(let [expected-search-items-count (search.ingestion/search-items-count)]
(memoize/memo-clear! @#'semantic.api/indexible-items-count)
(testing "Correctly reports empty index status"
@@ -39,8 +39,8 @@
(is (= 402 (get-in response [:data :status-code])))))))
(testing "with no active index"
(mt/with-premium-features #{:semantic-search}
- (with-redefs [semantic.env/get-pgvector-datasource! (constantly nil)
- semantic.env/get-index-metadata (constantly nil)]
+ (mt/with-dynamic-fn-redefs [semantic.env/get-pgvector-datasource! (constantly nil)
+ semantic.env/get-index-metadata (constantly nil)]
(let [response (mt/user-http-request :crowberto :get 200 "ee/semantic-search/status")]
(testing "returns empty map when no index is active"
(is (= {} response)))))))))
@@ -59,7 +59,7 @@
(semantic.tu/with-test-db! {:mode :mock-indexed}
(let [original-index semantic.tu/mock-index
original-table-name (:table-name original-index)
- new-index (with-redefs [semantic.index/model-table-suffix (constantly 345)]
+ new-index (mt/with-dynamic-fn-redefs [semantic.index/model-table-suffix (constantly 345)]
(#'semantic.pgvector-api/fresh-index semantic.tu/mock-index-metadata semantic.tu/mock-embedding-model :force-reset? true))
new-table-name (:table-name new-index)
pgvector (semantic.env/get-pgvector-datasource!)]
@@ -69,7 +69,7 @@
(is (=? original-index (:index best-index)))
(is (:active best-index)))
(testing "re-init creates the new index"
- (with-redefs [semantic.index/model-table-suffix (constantly 345)]
+ (mt/with-dynamic-fn-redefs [semantic.index/model-table-suffix (constantly 345)]
(let [response (mt/user-http-request :crowberto :post 200 "search/re-init")]
(is (contains? response :message))))
(is (not= original-table-name new-table-name))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/core_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/core_test.clj
index b30870bb3ff..985e0fca899 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/core_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/core_test.clj
@@ -40,25 +40,25 @@
reset-called-atoms! #(do (reset! semantic-called? false)
(reset! appdb-called? false)
(reset! legacy-called? false))]
- (with-redefs [semantic.pgvector-api/query
- (fn [& _]
- (reset! semantic-called? true)
- {:results [{:id 1 :name "semantic-result" :model "card" :collection_id 1 :score 0}]
- :raw-count 0})
- appdb/results
- (fn [_]
- (reset! appdb-called? true)
- [{:id 2 :name "appdb-result" :model "card" :collection_id 1 :score 0.9}])
- in-place.scoring/score-and-result
- (fn [result _]
- {:result (dissoc result :score)
- :score (:score result)})
- in-place.legacy/results
- (fn [_]
- (reset! legacy-called? true)
- (reify clojure.lang.IReduceInit
- (reduce [_this rf init]
- (reduce rf init [{:id 2 :name "legacy-result" :model "card" :collection_id 1 :score 0.7}]))))]
+ (mt/with-dynamic-fn-redefs [semantic.pgvector-api/query
+ (fn [& _]
+ (reset! semantic-called? true)
+ {:results [{:id 1 :name "semantic-result" :model "card" :collection_id 1 :score 0}]
+ :raw-count 0})
+ appdb/results
+ (fn [_]
+ (reset! appdb-called? true)
+ [{:id 2 :name "appdb-result" :model "card" :collection_id 1 :score 0.9}])
+ in-place.scoring/score-and-result
+ (fn [result _]
+ {:result (dissoc result :score)
+ :score (:score result)})
+ in-place.legacy/results
+ (fn [_]
+ (reset! legacy-called? true)
+ (reify clojure.lang.IReduceInit
+ (reduce [_this rf init]
+ (reduce rf init [{:id 2 :name "legacy-result" :model "card" :collection_id 1 :score 0.7}]))))]
(testing "API defaults to semantic engine when configured"
(let [response (mt/user-http-request :crowberto :get 200 "search" :q "test")]
(is @semantic-called? "Semantic search should be called by default")
@@ -129,24 +129,24 @@
metrics (atom {:metabase-search/semantic-fallback-results-usage 0
:metabase-search/semantic-fallback-triggered 0
:metabase-search/semantic-results-before-fallback 0})]
- (with-redefs [analytics/inc! (fn [metric & _args]
- (case metric
- :metabase-search/semantic-fallback-triggered
- (swap! metrics update
- :metabase-search/semantic-fallback-triggered
- inc))
- nil)
- analytics/observe! (fn [metric cnt]
- (case metric
- :metabase-search/semantic-fallback-results-usage
- (swap! metrics update
- :metabase-search/semantic-fallback-results-usage
- + cnt)
- :metabase-search/semantic-results-before-fallback
- (swap! metrics update
- :metabase-search/semantic-results-before-fallback
- + cnt))
- nil)]
+ (mt/with-dynamic-fn-redefs [analytics/inc! (fn [metric & _args]
+ (case metric
+ :metabase-search/semantic-fallback-triggered
+ (swap! metrics update
+ :metabase-search/semantic-fallback-triggered
+ inc))
+ nil)
+ analytics/observe! (fn [metric cnt]
+ (case metric
+ :metabase-search/semantic-fallback-results-usage
+ (swap! metrics update
+ :metabase-search/semantic-fallback-results-usage
+ + cnt)
+ :metabase-search/semantic-results-before-fallback
+ (swap! metrics update
+ :metabase-search/semantic-results-before-fallback
+ + cnt))
+ nil)]
(with-search-engine-mocks! [semantic-result] fallback-results
(fn []
(let [results (semantic.core/results search-ctx)]
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/dlq_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/dlq_test.clj
index 389720d19c6..b3035593fbe 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/dlq_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/dlq_test.clj
@@ -8,6 +8,7 @@
[metabase-enterprise.semantic-search.index :as semantic.index]
[metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]
[metabase-enterprise.semantic-search.test-util :as semantic.tu]
+ [metabase.test :as mt]
[metabase.util.json :as json]
[next.jdbc :as jdbc]
[next.jdbc.result-set :as jdbc.rs])
@@ -229,7 +230,7 @@
;; add everything to dlq
(add-gate-to-dlq! pgvector index-metadata @index-id-ref)
(vreset! clock-ref (.plus (.instant clock) semantic.dlq/initial-backoff))
- (with-redefs [semantic.index/upsert-index! (fn [& _] (throw (RuntimeException. "Forced failure")))]
+ (mt/with-dynamic-fn-redefs [semantic.index/upsert-index! (fn [& _] (throw (RuntimeException. "Forced failure")))]
(let [result (semantic.dlq/dlq-retry-loop! pgvector index-metadata index @index-id-ref
:max-run-duration (Duration/ofSeconds 1)
:max-batch-size 10)]
@@ -298,13 +299,13 @@
(is (= {"card_1" 1 "card_2" 1} (frequencies (map :id (:successes outcome)))))
(is (= {} (frequencies (map :gate_id (:failures outcome)))))))
(testing "failures across upsert/delete are aggregated"
- (with-redefs [semantic.index/upsert-index! (fn [& _] (throw (RuntimeException. "Upsert failed")))
- semantic.index/delete-from-index! (fn [& _] (throw (RuntimeException. "Delete failed")))]
+ (mt/with-dynamic-fn-redefs [semantic.index/upsert-index! (fn [& _] (throw (RuntimeException. "Upsert failed")))
+ semantic.index/delete-from-index! (fn [& _] (throw (RuntimeException. "Delete failed")))]
(let [outcome (semantic.dlq/try-batch! pgvector index gate-docs)]
(is (= {"card_1" 1 "card_2" 1} (frequencies (map (comp :gate_id :dlq-entry) (:failures outcome)))))
(is (= {} (frequencies (map :id (:successes outcome))))))))
(testing "partial failure is representable"
- (with-redefs [semantic.index/upsert-index! (fn [& _] (throw (RuntimeException. "Upsert failed")))]
+ (mt/with-dynamic-fn-redefs [semantic.index/upsert-index! (fn [& _] (throw (RuntimeException. "Upsert failed")))]
(let [outcome (semantic.dlq/try-batch! pgvector index gate-docs)]
(is (= {"card_1" 1} (frequencies (map (comp :gate_id :dlq-entry) (:failures outcome)))))
(is (= {"card_2" 1} (frequencies (map :id (:successes outcome))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/gate_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/gate_test.clj
index 529e68d596b..b77feeae078 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/gate_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/gate_test.clj
@@ -9,7 +9,7 @@
[metabase-enterprise.semantic-search.index :as semantic.index]
[metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]
[metabase-enterprise.semantic-search.test-util :as semantic.tu]
- [metabase.test.util :as mt]
+ [metabase.test :as mt]
[metabase.util :as u]
[metabase.util.json :as json]
[next.jdbc :as jdbc]
@@ -324,10 +324,10 @@
(is (== 4 (mt/metric-value system :metabase-search/semantic-gate-write-documents)))
(is (== 2 (mt/metric-value system :metabase-search/semantic-gate-write-modified))))
(testing ":metabase-search/semantic-gate-timeout-ms is updated on timeout"
- (with-redefs [semantic.gate/execute-upsert!
- (fn [& _] (throw (org.postgresql.util.PSQLException.
- "ERROR: canceling statement due to statement timeout"
- org.postgresql.util.PSQLState/QUERY_CANCELED)))]
+ (mt/with-dynamic-fn-redefs [semantic.gate/execute-upsert!
+ (fn [& _] (throw (org.postgresql.util.PSQLException.
+ "ERROR: canceling statement due to statement timeout"
+ org.postgresql.util.PSQLState/QUERY_CANCELED)))]
(let [ex (try
(sut pgvector index-metadata docs)
(catch Exception e e))]
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 3e18c208144..7dfad388827 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/indexer_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/indexer_test.clj
@@ -9,7 +9,8 @@
[metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata]
[metabase-enterprise.semantic-search.indexer :as semantic.indexer]
[metabase-enterprise.semantic-search.test-util :as semantic.tu]
- [metabase.test.util :as mt]
+ [metabase.test :as mt]
+ [metabase.test.util :as tu]
[metabase.util :as u]
[metabase.util.log :as log]
[next.jdbc :as jdbc]
@@ -143,7 +144,7 @@
(mt/with-prometheus-system! [_ system]
(testing "idle behavior based on novelty ratio"
(let [indexing-state (volatile! {:last-poll-count 100 :last-novel-count 30})
- original-sleep-fn @#'semantic.indexer/sleep
+ original-sleep-fn (mt/original-fn #'semantic.indexer/sleep)
sleep-metric-state (volatile! 0)
test-sleep-metric (fn []
(testing "Sleep metric grows"
@@ -151,30 +152,30 @@
(is (< @sleep-metric-state current-sleep))
(vreset! sleep-metric-state current-sleep))))]
(testing "high novelty ratio (>25%) - no sleep"
- (with-redefs [semantic.indexer/sleep (fn [ms] (throw (ex-info "Should not sleep" {:ms ms})))]
+ (mt/with-dynamic-fn-redefs [semantic.indexer/sleep (fn [ms] (throw (ex-info "Should not sleep" {:ms ms})))]
(is (nil? (semantic.indexer/on-indexing-idle indexing-state)))))
(testing "medium novelty ratio (10-25%) - small backoff"
(vswap! indexing-state assoc :last-novel-count 15) ; 15% novelty
(let [sleep-called (atom nil)]
- (with-redefs [semantic.indexer/sleep (fn [ms]
- (original-sleep-fn ms)
- (reset! sleep-called ms)) #_#(reset! sleep-called %)]
+ (mt/with-dynamic-fn-redefs [semantic.indexer/sleep (fn [ms]
+ (original-sleep-fn ms)
+ (reset! sleep-called ms)) #_#(reset! sleep-called %)]
(semantic.indexer/on-indexing-idle indexing-state)
(is (= 250 @sleep-called))
(test-sleep-metric))))
(testing "low novelty ratio (1-10%) - medium backoff"
(vswap! indexing-state assoc :last-novel-count 5) ; 5% novelty
(let [sleep-called (atom nil)]
- (with-redefs [semantic.indexer/sleep (fn [ms]
- (original-sleep-fn ms)
- (reset! sleep-called ms)) #_#(reset! sleep-called %)]
+ (mt/with-dynamic-fn-redefs [semantic.indexer/sleep (fn [ms]
+ (original-sleep-fn ms)
+ (reset! sleep-called ms)) #_#(reset! sleep-called %)]
(semantic.indexer/on-indexing-idle indexing-state)
(is (= 1500 @sleep-called))
(test-sleep-metric))))
(testing "very low novelty ratio (<1%) - big backoff"
(vswap! indexing-state assoc :last-novel-count 0) ; 0% novelty
(let [sleep-called (atom nil)]
- (with-redefs [semantic.indexer/sleep #(reset! sleep-called %)]
+ (mt/with-dynamic-fn-redefs [semantic.indexer/sleep #(reset! sleep-called %)]
(semantic.indexer/on-indexing-idle indexing-state)
(is (= 3000 @sleep-called)))))))))
@@ -218,17 +219,17 @@
:else (recur)))))
step-called (promise)
idle-called (promise)]
- (with-redefs [semantic.indexer/on-indexing-idle (fn [_]
- (deliver idle-called true)
- (swap! call-counter update :idle inc)
- (when (.isInterrupted (Thread/currentThread))
- (throw (InterruptedException.))))
- semantic.indexer/indexing-step (fn [& _]
- (deliver step-called true)
- (swap! call-counter update :step inc)
- (when-some [ex @step-ex] (throw ex))
- (when (.isInterrupted (Thread/currentThread))
- (throw (InterruptedException.))))]
+ (mt/with-dynamic-fn-redefs [semantic.indexer/on-indexing-idle (fn [_]
+ (deliver idle-called true)
+ (swap! call-counter update :idle inc)
+ (when (.isInterrupted (Thread/currentThread))
+ (throw (InterruptedException.))))
+ semantic.indexer/indexing-step (fn [& _]
+ (deliver step-called true)
+ (swap! call-counter update :step inc)
+ (when-some [ex @step-ex] (throw ex))
+ (when (.isInterrupted (Thread/currentThread))
+ (throw (InterruptedException.))))]
(with-open [loop-thread
(open-loop-thread! pgvector
index-metadata
@@ -276,14 +277,14 @@
(let [run-time (u/start-timer)
indexing-state (semantic.indexer/init-indexing-state (get-metadata-row! pgvector index-metadata index))]
(vswap! indexing-state assoc :max-run-duration (Duration/ofMillis 1))
- (with-redefs [semantic.indexer/sleep (fn [_])]
+ (mt/with-dynamic-fn-redefs [semantic.indexer/sleep (fn [_])]
(with-open [loop-thread (open-loop-thread! pgvector
index-metadata
index
indexing-state)]
(let [{:keys [^Thread thread caught-ex]} @loop-thread]
(testing "exits"
- (is (mt/poll-until 1000 (not (.isAlive thread))))
+ (is (tu/poll-until 1000 (not (.isAlive thread))))
(testing "did not wait too long"
(is (<= (u/since-ms run-time) 500)))
(testing "did not crash"
@@ -291,14 +292,14 @@
(testing "exists early if no new records after a time"
(let [run-time (u/start-timer)
indexing-state (semantic.indexer/init-indexing-state (get-metadata-row! pgvector index-metadata index))
- upsert-index! semantic.index/upsert-index!
+ upsert-index! (mt/original-fn #'semantic.index/upsert-index!)
indexed (atom [])]
(vswap! indexing-state assoc :exit-early-cold-duration (Duration/ofMillis 1))
- (with-redefs [semantic.indexer/sleep (fn [_])
- semantic.index/upsert-index! (fn [pgvector index docs]
- (let [docs (vec docs)]
- (swap! indexed into docs)
- (upsert-index! pgvector index docs)))]
+ (mt/with-dynamic-fn-redefs [semantic.indexer/sleep (fn [_])
+ semantic.index/upsert-index! (fn [pgvector index docs]
+ (let [docs (vec docs)]
+ (swap! indexed into docs)
+ (upsert-index! pgvector index docs)))]
;; need some data first for early exit, or it does nothing
(semantic.gate/gate-documents! pgvector index-metadata [(version c1 t1)])
(with-open [loop-thread (open-loop-thread! pgvector
@@ -307,7 +308,7 @@
indexing-state)]
(let [{:keys [^Thread thread caught-ex]} @loop-thread]
(testing "exits"
- (is (mt/poll-until 1000 (not (.isAlive thread))))
+ (is (tu/poll-until 1000 (not (.isAlive thread))))
(testing "has seen our row before exiting"
(is (= 1 (count @indexed))))
(testing "did not wait too long"
@@ -370,8 +371,8 @@
metadata-row {:indexer_last_poll (ts "2025-01-01T12:00:00Z")
:indexer_last_seen (ts "2025-01-01T11:30:00Z")}
index {:table-name "foo"}]
- (with-redefs [semantic.index-metadata/get-active-index-state (fn [& _] {:index index :metadata-row metadata-row})
- semantic.indexer/indexing-loop (fn [& args] (swap! loop-args conj args) nil)]
+ (mt/with-dynamic-fn-redefs [semantic.index-metadata/get-active-index-state (fn [& _] {:index index :metadata-row metadata-row})
+ semantic.indexer/indexing-loop (fn [& args] (swap! loop-args conj args) nil)]
(with-open [job-thread ^Closeable (open-job-thread pgvector index-metadata)]
(let [{:keys [caught-ex ^Thread thread]} @job-thread]
(testing "thread exited (loop returned)"
@@ -387,8 +388,8 @@
(AssertionError. "Assert")
(InterruptedException. "Interrupt")]]
(testing "exit on exception/error during loop"
- (with-redefs [semantic.index-metadata/get-active-index-state (fn [& _] {:index {} :metadata-row {}})
- semantic.indexer/indexing-loop (fn [& _] (throw ex))]
+ (mt/with-dynamic-fn-redefs [semantic.index-metadata/get-active-index-state (fn [& _] {:index {} :metadata-row {}})
+ semantic.indexer/indexing-loop (fn [& _] (throw ex))]
(with-open [job-thread ^Closeable (open-job-thread pgvector index-metadata)]
(let [{:keys [caught-ex ^Thread thread]} @job-thread]
(testing "thread exited"
@@ -543,7 +544,7 @@
(testing "indexing failure marks as stalled"
(let [indexing-state (fresh-indexing-state)]
(semantic.gate/gate-documents! pgvector index-metadata [(version (card 2) t1)])
- (with-redefs [semantic.index/upsert-index! (fn [& _] (throw (RuntimeException. "Index failure")))]
+ (mt/with-dynamic-fn-redefs [semantic.index/upsert-index! (fn [& _] (throw (RuntimeException. "Index failure")))]
(is (thrown? RuntimeException (semantic.indexer/indexing-step pgvector index-metadata index indexing-state)))
(is (some? (:indexer_stalled_at (get-metadata-row! pgvector index-metadata index)))))
(test-metric-growth))
@@ -555,7 +556,7 @@
(is (= stall-time (:stalled-at @indexing-state)))
;; Advance clock but (just about) stay within grace period
(vreset! clock-ref (.plus initial-clock (.minus semantic.indexer/stall-grace-period (Duration/ofSeconds 1))))
- (with-redefs [semantic.index/upsert-index! (fn [& _] (throw (RuntimeException. "Still failing during grace period")))]
+ (mt/with-dynamic-fn-redefs [semantic.index/upsert-index! (fn [& _] (throw (RuntimeException. "Still failing during grace period")))]
(is (thrown? RuntimeException (semantic.indexer/indexing-step pgvector index-metadata index indexing-state))))
;; Stall time should not be overwritten (retains original lower value)
(let [current-stall-time (:indexer_stalled_at (get-metadata-row! pgvector index-metadata index))]
@@ -579,7 +580,7 @@
(.plus semantic.indexer/stall-grace-period)
(.plus (Duration/ofSeconds 1))))
(semantic.gate/gate-documents! pgvector index-metadata [(version (card 4) t1)])
- (with-redefs [semantic.index/upsert-index! (fn [& _] (throw (RuntimeException. "Still failing")))]
+ (mt/with-dynamic-fn-redefs [semantic.index/upsert-index! (fn [& _] (throw (RuntimeException. "Still failing")))]
(semantic.indexer/indexing-step pgvector index-metadata index indexing-state)
(testing "DLQ entries created"
(let [dlq-rows (get-dlq-rows! pgvector index-metadata @index-id-ref)]
@@ -660,27 +661,27 @@
(with-open [loop-thread (open-loop-thread! pgvector index-metadata index (fresh-indexing-state))]
(let [{:keys [^Thread thread]} @loop-thread]
(testing "stall is cleared (dlq allowed us to seek to the gate tail)"
- (is (mt/poll-until
+ (is (tu/poll-until
1000
(nil? (:indexer_stalled_at (get-metadata-row! pgvector index-metadata index))))))
(testing "good docs get indexed right away, despite the poison"
- (is (mt/poll-until
+ (is (tu/poll-until
1000
(= (frequencies (map :id good-docs))
(frequencies (map :model_id (get-indexed-docs)))))))
(testing "only 1 dlq entry left"
- (is (mt/poll-until
+ (is (tu/poll-until
1000
(= 1 (count (get-dlq-rows! pgvector index-metadata @index-id-ref))))))
(testing "clear the poison"
(vreset! poisoned-doc-id nil)
(testing "all docs get indexed"
- (is (mt/poll-until
+ (is (tu/poll-until
1000
(= (frequencies (map :id all-docs))
(frequencies (map :model_id (get-indexed-docs))))))))
(testing "dlq drained"
- (is (mt/poll-until
+ (is (tu/poll-until
1000
(empty? (get-dlq-rows! pgvector index-metadata @index-id-ref)))))
(.interrupt thread)
@@ -695,13 +696,12 @@
:indexer_last_seen (ts "2025-01-01T11:30:00Z")}
index {:table-name "foo"}]
(testing ":metabase-search/semantic-indexer-loop-ms"
- (with-redefs [semantic.index-metadata/get-active-index-state
- (fn [& _]
- {:index index :metadata-row metadata-row})
-
- semantic.indexer/indexing-loop
- (fn [& _]
- (Thread/sleep 200)
- nil)]
+ (mt/with-dynamic-fn-redefs [semantic.index-metadata/get-active-index-state
+ (fn [& _]
+ {:index index :metadata-row metadata-row})
+ semantic.indexer/indexing-loop
+ (fn [& _]
+ (Thread/sleep 200)
+ nil)]
(semantic.indexer/quartz-job-run! pgvector index-metadata)
(is (<= 0.2 (mt/metric-value system :metabase-search/semantic-indexer-loop-ms))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/pgvector_api_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/pgvector_api_test.clj
index 09a1cb4de0b..9c134ce8069 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/pgvector_api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/pgvector_api_test.clj
@@ -186,9 +186,9 @@
(is (= api-results index-results))))
;; it would be better to test permissions at a higher level than we currently do, but for now to save time...
(testing "assumption: permissions are applied at the index query level, check the expected fn is called"
- (let [query-index semantic.index/query-index
+ (let [query-index (mt/original-fn #'semantic.index/query-index)
called (atom false)]
- (with-redefs [semantic.index/query-index (fn [& args] (reset! called true) (apply query-index args))]
+ (mt/with-dynamic-fn-redefs [semantic.index/query-index (fn [& args] (reset! called true) (apply query-index args))]
(sut pgvector index-metadata search)
(is @called))))
(testing "same results after reinit"
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/repair_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/repair_test.clj
index 069d5eb305b..b3d5fff638d 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/repair_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/repair_test.clj
@@ -99,7 +99,7 @@
(semantic.tu/index-all!)
(testing "repair table is cleaned up after successful repair"
(let [test-repair-table-name "repair_table_cleanup_test"]
- (with-redefs [semantic.repair/repair-table-name (constantly test-repair-table-name)]
+ (mt/with-dynamic-fn-redefs [semantic.repair/repair-table-name (constantly test-repair-table-name)]
(semantic.core/repair-index! [(create-test-document "card" 7 "New Test Card")])
(let [gate-contents (gate-table-contents pgvector gate-table)]
(is (tombstone? (gate-entry-by-id gate-contents "card_6")))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/task/index_cleanup_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/task/index_cleanup_test.clj
index efd2a74715c..f9b62da33a6 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/task/index_cleanup_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/task/index_cleanup_test.clj
@@ -100,8 +100,8 @@
(is (semantic.tu/table-exists-in-db? recent-table))
(is (semantic.tu/table-exists-in-db? active-table))
;; Run cleanup function and ensure only the stale & orphaned tables is dropped
- (with-redefs [semantic.env/get-pgvector-datasource! (constantly pgvector)
- semantic.env/get-index-metadata (constantly index-metadata)]
+ (mt/with-dynamic-fn-redefs [semantic.env/get-pgvector-datasource! (constantly pgvector)
+ semantic.env/get-index-metadata (constantly index-metadata)]
(mt/with-temporary-setting-values [semantic.settings/stale-index-retention-hours retention-hours]
(cleanup-stale-indexes! pgvector index-metadata)))
(is (not (semantic.tu/table-exists-in-db? stale-table)))
@@ -122,9 +122,9 @@
:vector-dimensions 1024
:index-created-at old-time})
(is (not (semantic.tu/table-exists-in-db? nonexistent-table)))
- (with-redefs [semantic.settings/stale-index-retention-hours (constantly retention-hours)
- semantic.env/get-pgvector-datasource! (constantly pgvector)
- semantic.env/get-index-metadata (constantly index-metadata)]
+ (mt/with-dynamic-fn-redefs [semantic.settings/stale-index-retention-hours (constantly retention-hours)
+ semantic.env/get-pgvector-datasource! (constantly pgvector)
+ semantic.env/get-index-metadata (constantly index-metadata)]
(cleanup-stale-indexes! pgvector index-metadata)
(is (not (semantic.tu/table-exists-in-db? nonexistent-table))))))))))
@@ -242,7 +242,7 @@
(jdbc/execute! pgvector [(format "CREATE TABLE \"%s\" (id INT)" old-repair-table-name)])
(jdbc/execute! pgvector [(format "CREATE TABLE \"%s\" (id INT)" recent-repair-table-name)])
(jdbc/execute! pgvector [(format "CREATE TABLE \"%s\" (id INT)" non-repair-table-name)])
- (with-redefs [semantic.settings/repair-table-retention-hours (constantly retention-hours)]
+ (mt/with-dynamic-fn-redefs [semantic.settings/repair-table-retention-hours (constantly retention-hours)]
(let [orphan-tables (#'sut/orphan-repair-tables pgvector)]
(is (= #{old-repair-table-name} (set orphan-tables))
"Only old repair table should be detected as orphan"))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/task/metric_collector_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/task/metric_collector_test.clj
index 8b79c286b1e..b2b63a40733 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/task/metric_collector_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/task/metric_collector_test.clj
@@ -70,8 +70,8 @@
(let [pgvector (semantic.env/get-pgvector-datasource!)
index-metadata (semantic.tu/unique-index-metadata)
model semantic.tu/mock-embedding-model]
- (with-redefs [semantic.env/get-index-metadata (fn [] index-metadata)
- semantic.env/get-configured-embedding-model (fn [] model)]
+ (mt/with-dynamic-fn-redefs [semantic.env/get-index-metadata (fn [] index-metadata)
+ semantic.env/get-configured-embedding-model (fn [] model)]
(testing "Missing tables are handled gracefully"
(let [result (try
(@#'semantic.task.collector/collect-metrics!)
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/cmd_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/cmd_test.clj
index 417f926dd7e..721633fcb71 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/cmd_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/cmd_test.clj
@@ -21,8 +21,8 @@
(ts/with-random-dump-dir [dump-dir "serdesv2-"]
(.mkdirs (io/file dump-dir))
(.setWritable (io/file dump-dir) false)
- (with-redefs [v2.extract/extract (fn [& _args]
- (throw (ex-info "Do not call me!" {})))]
+ (mt/with-dynamic-fn-redefs [v2.extract/extract (fn [& _args]
+ (throw (ex-info "Do not call me!" {})))]
(is (thrown-with-msg? Exception #"Destination path is not writeable: "
(cmd/export dump-dir))))))))
@@ -63,8 +63,8 @@
"success" true
"error_message" nil}
(-> (snowplow-test/pop-event-data-and-user-id!) first :data))))
- (with-redefs [v2.storage/store! (fn [_stream _backend]
- (throw (Exception. "Cannot load settings")))]
+ (mt/with-dynamic-fn-redefs [v2.storage/store! (fn [_stream _backend]
+ (throw (Exception. "Cannot load settings")))]
(is (thrown? Exception
(cmd/export dump-dir "--collection" (str (:id coll)) "--no-data-model")))
(testing "Snowplow export event about error was sent"
@@ -84,13 +84,13 @@
(->> (map :data (snowplow-test/pop-event-data-and-user-id!))
(filter #(= "serialization" (get % "event")))
first)))))
- (let [ingest-file @#'v2.ingest/ingest-file]
+ (let [ingest-file (mt/original-fn #'v2.ingest/ingest-file)]
;; overriding ingest-file is weird, but ingest-one is a protocol function and with-redefs won't
;; override that reliably
- (with-redefs [v2.ingest/ingest-file (fn [^java.io.File file]
- (cond-> (ingest-file file)
- (= (.getName file) "card.yaml")
- (assoc :collection_id "DoesNotExist")))]
+ (mt/with-dynamic-fn-redefs [v2.ingest/ingest-file (fn [^java.io.File file]
+ (cond-> (ingest-file file)
+ (= (.getName file) "card.yaml")
+ (assoc :collection_id "DoesNotExist")))]
(is (thrown? Exception
(cmd/import dump-dir)))
(testing "Snowplow import event about error was sent"
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj
index d7ed3588aae..bd340a124f9 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj
@@ -2026,10 +2026,10 @@
(testing "visualizer settings transform entity IDs <-> card IDs"
(let [card-entity-id "WcMlLFNVcy0iO49mKW3WH"
card-id 621]
- (with-redefs [serdes/*import-fk* (fn [_entity-id _model]
- card-id)
- serdes/*export-fk* (fn [_card-id _model]
- card-entity-id)]
+ (mt/with-dynamic-fn-redefs [serdes/*import-fk* (fn [_entity-id _model]
+ card-id)
+ serdes/*export-fk* (fn [_card-id _model]
+ card-entity-id)]
(testing "transforms sourceId in column mappings"
(let [input {:visualization
{:columnValuesMapping
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj
index 416375ba27a..c9fd54e816f 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj
@@ -1632,11 +1632,11 @@
:model/Card c2 {:name "card2" :collection_id (:id coll)}
:model/Card _c3 {:name "card3" :collection_id (:id coll)}]
(testing "It's possible to skip a few errors during extract"
- (let [extract-one serdes/extract-one]
- (with-redefs [serdes/extract-one (fn [model-name opts instance]
- (if (= (:entity_id instance) (:entity_id c1))
- (throw (ex-info "Skip me" {}))
- (extract-one model-name opts instance)))]
+ (let [extract-one (mt/original-fn #'serdes/extract-one)]
+ (mt/with-dynamic-fn-redefs [serdes/extract-one (fn [model-name opts instance]
+ (if (= (:entity_id instance) (:entity_id c1))
+ (throw (ex-info "Skip me" {}))
+ (extract-one model-name opts instance)))]
(mt/with-log-messages-for-level [messages [metabase.models.serialization :warn]]
(let [ser (vec (serdes.extract/extract {:no-settings true
:no-data-model true
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/storage_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/storage_test.clj
index 3203646cb87..1c4240c51ca 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/storage_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/storage_test.clj
@@ -190,12 +190,12 @@
(map? v) (descend v (conj path k))
(and (sequential? v)
(map? (first v))) (run! #(descend % (conj path k)) v))))))]
- (with-redefs [spit (fn [fname yaml-data]
- (testing (format "File %s\n" fname)
- (let [coll (yaml/parse-string yaml-data)]
- (if (str/ends-with? fname "settings.yaml")
- (descend coll [:settings])
- (descend coll)))))]
+ (mt/with-dynamic-fn-redefs [spit (fn [fname yaml-data]
+ (testing (format "File %s\n" fname)
+ (let [coll (yaml/parse-string yaml-data)]
+ (if (str/ends-with? fname "settings.yaml")
+ (descend coll [:settings])
+ (descend coll)))))]
(storage/store! export (storage.files/file-writer dump-dir))))))))
(deftest store-error-test
@@ -291,11 +291,11 @@
;; Export again but with nested entity query results reversed,
;; simulating non-deterministic DB row ordering (as seen on Aurora Postgres)
- original-fn @#'serdes/transform->nested
+ original-fn (mt/original-fn #'serdes/transform->nested)
yaml-reversed
- (with-redefs [serdes/transform->nested
- (fn [transform opts batch]
- (update-vals (original-fn transform opts batch) reverse))]
+ (mt/with-dynamic-fn-redefs [serdes/transform->nested
+ (fn [transform opts batch]
+ (update-vals (original-fn transform opts batch) reverse))]
(clean-and-export!))]
(testing "Dashcard ordering should be stable regardless of DB return order"
(is (= yaml-before yaml-reversed)
diff --git a/enterprise/backend/test/metabase_enterprise/snippet_collections/models/native_query_snippet/permissions_test.clj b/enterprise/backend/test/metabase_enterprise/snippet_collections/models/native_query_snippet/permissions_test.clj
index f06d80c29ec..5d9b3b90898 100644
--- a/enterprise/backend/test/metabase_enterprise/snippet_collections/models/native_query_snippet/permissions_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/snippet_collections/models/native_query_snippet/permissions_test.clj
@@ -29,14 +29,14 @@
(testing "if EE perms aren't enabled: "
(mt/with-premium-features #{}
(testing "should NOT be allowed if you don't have native perms for at least one DB"
- (with-redefs [snippet.perms/has-any-native-permissions? (constantly false)]
+ (mt/with-dynamic-fn-redefs [snippet.perms/has-any-native-permissions? (constantly false)]
(test-perms* false)))
(testing "should be allowed if you have native perms for at least one DB"
- (with-redefs [snippet.perms/has-any-native-permissions? (constantly true)]
+ (mt/with-dynamic-fn-redefs [snippet.perms/has-any-native-permissions? (constantly true)]
(test-perms* true)))))
(testing "if EE perms are enabled: "
(mt/with-premium-features #{:snippet-collections}
- (with-redefs [snippet.perms/has-any-native-permissions? (constantly true)]
+ (mt/with-dynamic-fn-redefs [snippet.perms/has-any-native-permissions? (constantly true)]
(testing "should be allowed if you have collection perms, native perms for at least one DB, and are not sandboxed"
(grant-collection-perms!)
(test-perms* true))
@@ -47,7 +47,7 @@
(testing "should NOT be allowed if you are sandboxed"
(met/with-gtaps! {:gtaps {:venues {:query (mt/mbql-query venues)}}}
(test-perms* false))))
- (with-redefs [snippet.perms/has-any-native-permissions? (constantly false)]
+ (mt/with-dynamic-fn-redefs [snippet.perms/has-any-native-permissions? (constantly false)]
(testing "should NOT be allowed if you do not have native query perms for at least one DB"
(test-perms* false)))))))
diff --git a/enterprise/backend/test/metabase_enterprise/sso/api/oidc_test.clj b/enterprise/backend/test/metabase_enterprise/sso/api/oidc_test.clj
index b8ba9c0124b..163b768d65e 100644
--- a/enterprise/backend/test/metabase_enterprise/sso/api/oidc_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sso/api/oidc_test.clj
@@ -45,7 +45,7 @@
(deftest create-provider-test
(testing "Creating an OIDC provider"
(mt/with-additional-premium-features #{:sso-oidc}
- (with-redefs [oidc.check/check-oidc-configuration (constantly successful-check-result)]
+ (mt/with-dynamic-fn-redefs [oidc.check/check-oidc-configuration (constantly successful-check-result)]
(mt/with-temporary-setting-values [oidc-providers []]
(testing "successfully creates provider"
(let [result (mt/user-http-request :crowberto :post 200 "ee/sso/oidc" test-provider)]
@@ -78,7 +78,7 @@
(deftest update-provider-test
(testing "Updating an OIDC provider"
(mt/with-additional-premium-features #{:sso-oidc}
- (with-redefs [oidc.check/check-oidc-configuration (constantly successful-check-result)]
+ (mt/with-dynamic-fn-redefs [oidc.check/check-oidc-configuration (constantly successful-check-result)]
(mt/with-temporary-setting-values [oidc-providers [test-provider]]
(testing "successfully updates login prompt"
(let [result (mt/user-http-request :crowberto :put 200 "ee/sso/oidc/test-okta"
diff --git a/enterprise/backend/test/metabase_enterprise/sso/api/sso_test.clj b/enterprise/backend/test/metabase_enterprise/sso/api/sso_test.clj
index 4f2489e6fb8..d37e88b0063 100644
--- a/enterprise/backend/test/metabase_enterprise/sso/api/sso_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sso/api/sso_test.clj
@@ -29,7 +29,7 @@
site-url "http://localhost:3000"
saml-slo-enabled true
saml-identity-provider-slo-uri "http://idp.example.com/logout"]
- (with-redefs [random-uuid (constantly "66d96ab4-9834-40db-a3cd-42b361503ab9")]
+ (mt/with-dynamic-fn-redefs [random-uuid (constantly "66d96ab4-9834-40db-a3cd-42b361503ab9")]
(binding [client/*url-prefix* ""]
(mt/with-temp [:model/User user {:email "[email protected]" :sso_source "saml"}
:model/Session {session-id :id} {:user_id (:id user) :id (session/generate-session-id) :key_hashed (session/hash-session-key (session/generate-session-key))}]
@@ -120,8 +120,8 @@
;; existing login history so it's not the user's first login ever
:model/LoginHistory _ {:user_id user-id
:device_id "existing-device"}]
- (with-redefs [messages/send-login-from-new-device-email! (fn [info]
- (swap! emails-sent conj info))]
+ (mt/with-dynamic-fn-redefs [messages/send-login-from-new-device-email! (fn [info]
+ (swap! emails-sent conj info))]
(let [jwt-token (create-valid-jwt-token {:email email-addr})
response (mt/client :post 200 "/auth/sso/to_session" {:jwt jwt-token})]
(is (string? (:session_token response)))
diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj
index 6016bbbb480..6a22edf5fdf 100644
--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj
@@ -568,6 +568,8 @@
;; deactivate the user again
(t2/update! :model/User :email "[email protected]" {:is_active false})
(is (not (t2/select-one-fn :is_active :model/User :email "[email protected]")))
+ ;; with-redefs (cross-thread): /auth/sso runs on Jetty workers that don't inherit *local-redefs*
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [sso-settings/jwt-user-provisioning-enabled? (constantly false)
appearance.settings/site-name (constantly "test")]
(is (=? {:body "Sorry, but you'll need a test account to view this page. Please contact your administrator."}
@@ -758,6 +760,8 @@
:name "Tenant McTenantson"
:is_active false}
:model/User {existing-email :email} {:tenant_id tenant-id}]
+ ;; with-redefs (cross-thread): /auth/sso runs on Jetty workers that don't inherit *local-redefs*
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [sso-settings/jwt-user-provisioning-enabled? (constantly false)]
(testing "with user provisioning turned off"
(testing "a new user cannot log into a deactivated tenant, and the tenant doesn't get activated"
@@ -903,6 +907,8 @@
(deftest create-new-jwt-user-no-user-provisioning-test
(testing "When user provisioning is disabled, throw an error if we attempt to create a new user."
(with-jwt-default-setup!
+ ;; with-redefs (cross-thread): /auth/sso runs on Jetty workers that don't inherit *local-redefs*
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [sso-settings/jwt-user-provisioning-enabled? (constantly false)
appearance.settings/site-name (constantly "test")]
(is (=? {:body "Sorry, but you'll need a test account to view this page. Please contact your administrator."}
diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/ldap_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/ldap_test.clj
index 96226d8aaf4..df6f5d9b186 100644
--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/ldap_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/ldap_test.clj
@@ -287,6 +287,8 @@
(mt/with-model-cleanup [:model/User]
(ldap.test/with-ldap-server!
(testing "an error is thrown when a new user attempts to login via provider/login! and user provisioning is not enabled"
+ ;; with-redefs (cross-thread): /auth/sso runs on Jetty workers that don't inherit *local-redefs*
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [sso-settings/ldap-user-provisioning-enabled? (constantly false)
appearance.settings/site-name (constantly "test")]
(is (thrown-with-msg?
diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/oidc_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/oidc_test.clj
index c34c6cf91e8..8c785334d16 100644
--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/oidc_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/oidc_test.clj
@@ -236,6 +236,8 @@
(binding [*group-sync-claims* claims
*group-sync-email* email]
(with-group-sync-oidc!
+ ;; with-redefs (cross-thread): /auth/sso runs on Jetty workers that don't inherit *local-redefs*
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [oidc.state/validate-oidc-callback
(fn [_request _state _provider & _opts]
{:valid? true :nonce "test-nonce" :redirect "/"})]
diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj
index 4662ca76368..52c54c06d6c 100644
--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj
@@ -595,6 +595,8 @@
;; deactivate the user again
(t2/update! :model/User :%lower.email "[email protected]" {:is_active false})
(testing "We can't reactivate the user if user provisioning is disabled."
+ ;; with-redefs (cross-thread): /auth/sso runs on Jetty workers that don't inherit *local-redefs*
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [sso-settings/saml-user-provisioning-enabled? (constantly false)
appearance.settings/site-name (constantly "test")]
(let [req-options (saml-post-request-options (new-user-no-names-saml-test-response)
@@ -745,6 +747,8 @@
(testing "When user provisioning is disabled, throw an error if we attempt to create a new user."
(with-other-sso-types-disabled!
(with-saml-default-setup!
+ ;; with-redefs (cross-thread): /auth/sso runs on Jetty workers that don't inherit *local-redefs*
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [sso-settings/saml-user-provisioning-enabled? (constantly false)
appearance.settings/site-name (constantly "test")]
(let [req-options (saml-post-request-options (new-user-saml-test-response)
@@ -891,7 +895,9 @@
(with-saml-default-setup!
(do-with-some-validators-disabled!
(fn []
- ;; Mock the saml-response->attributes function to return mixed attribute types
+ ;; Mock the saml-response->attributes function to return mixed attribute types.
+ ;; with-redefs (cross-thread): /auth/sso runs on Jetty workers that don't inherit *local-redefs*
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [saml.p/saml-response->attributes
(fn [_]
{"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" "[email protected]"
@@ -1011,6 +1017,8 @@
response (client/client-real-response :post 302 "/auth/sso" req-options)]
(is (successful-login? response)))))
(testing "an existing user also fails to log in"
+ ;; with-redefs (cross-thread): /auth/sso runs on Jetty workers that don't inherit *local-redefs*
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [saml.p/saml-response->attributes
(fn [_]
{"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" existing-email
@@ -1030,6 +1038,8 @@
:name "Tenant McTenantson"
:is_active false}
:model/User {existing-email :email} {:tenant_id tenant-id}]
+ ;; with-redefs (cross-thread): /auth/sso runs on Jetty workers that don't inherit *local-redefs*
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [sso-settings/saml-user-provisioning-enabled? (constantly false)]
(do-with-some-validators-disabled!
(fn []
@@ -1040,6 +1050,8 @@
response (client/client-real-response :post 401 "/auth/sso" req-options)]
(is (not (successful-login? response))))))
(testing "an existing user also fails to log in"
+ ;; with-redefs (cross-thread): /auth/sso runs on Jetty workers that don't inherit *local-redefs*
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [saml.p/saml-response->attributes
(fn [_]
{"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" existing-email
@@ -1063,6 +1075,8 @@
(do-with-some-validators-disabled!
(fn []
(testing "tenant -> other tenant fails with correct error message"
+ ;; with-redefs (cross-thread): /auth/sso runs on Jetty workers that don't inherit *local-redefs*
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [saml.p/saml-response->attributes
(fn [_]
{"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" email-with-tenant
@@ -1084,7 +1098,9 @@
:model/User {email-with-tenant :email} {:tenant_id tenant-id}]
(do-with-some-validators-disabled!
(fn []
- ;; Use the regular new-user response which doesn't have tenant attribute
+ ;; Use the regular new-user response which doesn't have tenant attribute.
+ ;; with-redefs (cross-thread): /auth/sso runs on Jetty workers that don't inherit *local-redefs*
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [saml.p/saml-response->attributes
(fn [_]
{"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" email-with-tenant})]
@@ -1105,6 +1121,8 @@
:model/User {email-without-tenant :email} {:tenant_id nil}]
(do-with-some-validators-disabled!
(fn []
+ ;; with-redefs (cross-thread): /auth/sso runs on Jetty workers that don't inherit *local-redefs*
+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [saml.p/saml-response->attributes
(fn [_]
{"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" email-without-tenant
diff --git a/enterprise/backend/test/metabase_enterprise/support_access_grants/core_test.clj b/enterprise/backend/test/metabase_enterprise/support_access_grants/core_test.clj
index d2ebd3d0cc7..bc38c54c2f2 100644
--- a/enterprise/backend/test/metabase_enterprise/support_access_grants/core_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/support_access_grants/core_test.clj
@@ -252,7 +252,7 @@
:model/User {support-user-id :id} {:email support-email}]
(mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity]
(mt/with-temp-env-var-value! [mb-support-access-grant-email support-email]
- (with-redefs [sag.settings/support-access-grant-email (constantly support-email)]
+ (mt/with-dynamic-fn-redefs [sag.settings/support-access-grant-email (constantly support-email)]
(let [grant (grants/create-grant! creator-id 240 "SUPPORT-TOKEN-1" "test notes")]
(is (some? (:token grant)) "Token should be created")
(is (string? (:token grant)) "Token should be a string")
@@ -271,9 +271,9 @@
support-last-name "User"]
(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 support-email)
- sag.settings/support-access-grant-first-name (constantly support-first-name)
- sag.settings/support-access-grant-last-name (constantly support-last-name)]
+ (mt/with-dynamic-fn-redefs [sag.settings/support-access-grant-email (constantly support-email)
+ sag.settings/support-access-grant-first-name (constantly support-first-name)
+ sag.settings/support-access-grant-last-name (constantly support-last-name)]
(let [grant (grants/create-grant! creator-id 240 "SUPPORT-CREATE-USER" "test notes")
created-user (t2/select-one :model/User :email support-email)]
(is (some? created-user) "Support user should be created")
@@ -294,7 +294,7 @@
(mt/with-temp [:model/User {creator-id :id} {}
:model/User {support-user-id :id} {:email support-email :is_superuser false}]
(mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity]
- (with-redefs [sag.settings/support-access-grant-email (constantly support-email)]
+ (mt/with-dynamic-fn-redefs [sag.settings/support-access-grant-email (constantly support-email)]
(grants/create-grant! creator-id 240 "SUPPORT-ADMIN-1" "test notes")
(let [updated-user (t2/select-one :model/User :id support-user-id)]
(is (:is_superuser updated-user) "Support user should have admin access after grant creation")))))))
@@ -303,7 +303,7 @@
(mt/with-temp [:model/User {creator-id :id} {:is_superuser true}
:model/User {support-user-id :id} {:email support-email :is_superuser false}]
(mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity]
- (with-redefs [sag.settings/support-access-grant-email (constantly support-email)]
+ (mt/with-dynamic-fn-redefs [sag.settings/support-access-grant-email (constantly support-email)]
(let [grant (grants/create-grant! creator-id 240 "SUPPORT-ADMIN-2" "test notes")]
(grants/revoke-grant! creator-id (:id grant))
(let [updated-user (t2/select-one :model/User :id support-user-id)]
@@ -315,7 +315,7 @@
(mt/with-temp [:model/User {creator-id :id} {}
:model/User {support-user-id :id} {:email support-email :is_active false :is_superuser false}]
(mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity]
- (with-redefs [sag.settings/support-access-grant-email (constantly support-email)]
+ (mt/with-dynamic-fn-redefs [sag.settings/support-access-grant-email (constantly support-email)]
(grants/create-grant! creator-id 240 "SUPPORT-REACTIVATE-1" "test notes")
(let [updated-user (t2/select-one [:model/User :id :is_active :is_superuser] :id support-user-id)]
(is (:is_active updated-user) "Support user should be reactivated")
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 47a5a14893c..65a52a6dcba 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
@@ -24,9 +24,9 @@
(testing "POST /api/session/reset_password works with support access grant token"
(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-123" "Test notes")
token (:token grant)
new-password "NewSecurePassword123!"]
@@ -74,9 +74,9 @@
(testing "POST /api/session/reset_password rejects expired support access grant token"
(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 (t/with-clock (t/mock-clock (t/minus (t/instant) (t/weeks 5)))
(grants/create-grant! creator-id 60 "TICKET-123" "Test notes"))
token (:token grant)]
@@ -91,9 +91,9 @@
(testing "GET /api/session/password_reset_token_valid works with support access grant token"
(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-456" "Test notes")
token (:token grant)]
(is (some? token) "Token should be created")
@@ -121,9 +121,9 @@
(testing "GET /api/session/password_reset_token_valid returns false for expired support grant"
(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 (t/with-clock (t/mock-clock (t/minus (t/instant) (t/weeks 5)))
(grants/create-grant! creator-id 60 "TICKET-123" "Test notes"))
token (:token grant)]
@@ -137,9 +137,9 @@
(testing "POST /api/session/reset_password creates a session after successful password reset"
(mt/with-temp [:model/User {creator-id :id} {}]
(mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity :model/User :model/Session]
- (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-999" "Test notes")
token (:token grant)
new-password "SecurePassword123!"]
@@ -164,9 +164,9 @@
(mt/with-temp [:model/User {creator-id :id} {}]
(mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity :model/User]
(let [email "[email protected]"]
- (with-redefs [sag.settings/support-access-grant-email (constantly email)
- 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)
+ sag.settings/support-access-grant-first-name (constantly "Support")
+ sag.settings/support-access-grant-last-name (constantly "User")]
;; Step 1: Create the support user via an initial grant (simulates first-time setup)
(let [initial-grant (grants/create-grant! creator-id 60 "TICKET-INITIAL" "Initial setup")
initial-token (:token initial-grant)]
@@ -281,9 +281,9 @@
(mt/with-temp [:model/User {creator-id :id} {}]
(mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity :model/User]
(let [email "[email protected]"]
- (with-redefs [sag.settings/support-access-grant-email (constantly email)
- 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)
+ sag.settings/support-access-grant-first-name (constantly "Support")
+ sag.settings/support-access-grant-last-name (constantly "User")]
;; Create and use a first grant so the support user exists
(let [first-grant (grants/create-grant! creator-id 60 "TICKET-FIRST" "First grant")]
(mt/client :post 200 "session/reset_password"
diff --git a/modules/drivers/athena/test/metabase/driver/athena_test.clj b/modules/drivers/athena/test/metabase/driver/athena_test.clj
index 7c5dcad5a5a..07860232d3b 100644
--- a/modules/drivers/athena/test/metabase/driver/athena_test.clj
+++ b/modules/drivers/athena/test/metabase/driver/athena_test.clj
@@ -39,7 +39,7 @@
(deftest sync-test
(testing "sync with nested fields"
- (with-redefs [athena/run-query (constantly nested-schema)]
+ (mt/with-dynamic-fn-redefs [athena/run-query (constantly nested-schema)]
(is (= #{{:name "key"
:base-type :type/Integer
:database-type "int"
@@ -306,10 +306,10 @@
(let [db (mt/db)
table (t2/select-one :model/Table :db_id (:id db) :name "airport")
get-columns-called (volatile! false)]
- (with-redefs [athena/get-columns (fn [& _]
- (vreset! get-columns-called true)
- [{:column_name "c" :type_name "bigint"}
- {:column_name "c" :type_name "string"}])]
+ (mt/with-dynamic-fn-redefs [athena/get-columns (fn [& _]
+ (vreset! get-columns-called true)
+ [{:column_name "c" :type_name "bigint"}
+ {:column_name "c" :type_name "string"}])]
(is (= #{{:database-position 0, :name "id", :database-type "int", :base-type :type/Integer}
{:database-position 1, :name "name", :database-type "string", :base-type :type/Text}
{:database-position 2, :name "code", :database-type "string", :base-type :type/Text}
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 8512e1d4b80..005f849e50e 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
@@ -70,8 +70,8 @@
(testing "can-connect? returns false for bogus credentials"
(is (false? (driver/can-connect? :bigquery-cloud-sdk (assoc db-details :project-id fake-proj-id)))))
(testing "can-connect? returns true for a valid dataset-id even with no tables"
- (with-redefs [bigquery/describe-database-tables (fn [& _]
- [])]
+ (mt/with-dynamic-fn-redefs [bigquery/describe-database-tables (fn [& _]
+ [])]
(is (true? (driver/can-connect? :bigquery-cloud-sdk db-details)))))
(testing "can-connect? returns an appropriate exception message if no datasets are found"
(is (thrown-with-msg? Exception
@@ -1009,14 +1009,14 @@
(deftest retry-certain-exceptions-test
(mt/test-driver :bigquery-cloud-sdk
(let [fake-execute-called (atom false)
- orig-fn @#'bigquery/execute-bigquery]
+ orig-fn (mt/original-fn #'bigquery/execute-bigquery)]
(testing "Retry functionality works as expected"
- (with-redefs [bigquery/execute-bigquery (fn [& args]
- (if-not @fake-execute-called
- (do (reset! fake-execute-called true)
- ;; simulate a transient error being thrown
- (throw (ex-info "Transient error" {:retryable? true})))
- (apply orig-fn args)))]
+ (mt/with-dynamic-fn-redefs [bigquery/execute-bigquery (fn [& args]
+ (if-not @fake-execute-called
+ (do (reset! fake-execute-called true)
+ ;; simulate a transient error being thrown
+ (throw (ex-info "Transient error" {:retryable? true})))
+ (apply orig-fn args)))]
;; run any other test that requires a successful query execution
(table-rows-sample-test)
;; make sure that the fake exception was thrown, and thus the query execution was retried
@@ -1025,14 +1025,14 @@
(deftest not-retry-cancellation-exception-test
(mt/test-driver :bigquery-cloud-sdk
(let [fake-execute-called (atom false)
- orig-fn @#'bigquery/execute-bigquery]
+ orig-fn (mt/original-fn #'bigquery/execute-bigquery)]
(testing "Should not retry query on cancellation"
- (with-redefs [bigquery/execute-bigquery (fn [& args]
- (if (not @fake-execute-called)
- (do (reset! fake-execute-called true)
- ;; Simulate a cancellation happening
- (throw (ex-info "Query cancelled" {::bigquery/cancelled? true})))
- (apply orig-fn args)))]
+ (mt/with-dynamic-fn-redefs [bigquery/execute-bigquery (fn [& args]
+ (if (not @fake-execute-called)
+ (do (reset! fake-execute-called true)
+ ;; Simulate a cancellation happening
+ (throw (ex-info "Query cancelled" {::bigquery/cancelled? true})))
+ (apply orig-fn args)))]
(try
(qp/process-query {:native {:query "SELECT CURRENT_TIMESTAMP() AS notRetryCancellationExceptionTest"} :database (mt/id)
:type :native})
@@ -1086,7 +1086,7 @@
(mt/test-driver :bigquery-cloud-sdk
(testing "BigQuery queries which fail on later pages are caught properly"
(let [page-counter (atom 3)
- orig-exec @#'bigquery/reducible-bigquery-results
+ orig-exec (mt/original-fn #'bigquery/reducible-bigquery-results)
wrap-result (fn wrap-result [^TableResult result]
(proxy [TableResult] []
(getSchema [] (.getSchema result))
@@ -1096,8 +1096,8 @@
(if (zero? @page-counter)
nil
(wrap-result (.getNextPage result))))))]
- (with-redefs [bigquery/reducible-bigquery-results (fn [page & args]
- (apply orig-exec (wrap-result page) args))]
+ (mt/with-dynamic-fn-redefs [bigquery/reducible-bigquery-results (fn [page & args]
+ (apply orig-exec (wrap-result page) args))]
(binding [bigquery/*page-size* 10 ; small pages so there are several
bigquery/*page-callback* (fn []
(let [pages (swap! page-counter #(max (dec %) 0))]
@@ -1113,7 +1113,7 @@
(testing "BigQuery queries which fail on later pages are caught properly"
(let [count-before (count (future-thread-names))
page-counter (atom 3)
- orig-exec @#'bigquery/reducible-bigquery-results
+ orig-exec (mt/original-fn #'bigquery/reducible-bigquery-results)
wrap-result (fn wrap-result [^TableResult result]
(proxy [TableResult] []
(getSchema [] (.getSchema result))
@@ -1123,8 +1123,8 @@
(if (zero? @page-counter)
(throw (ex-info "onoes BigQuery failed to fetch a later page" {}))
(wrap-result (.getNextPage result))))))]
- (with-redefs [bigquery/reducible-bigquery-results (fn [page & args]
- (apply orig-exec (wrap-result page) args))]
+ (mt/with-dynamic-fn-redefs [bigquery/reducible-bigquery-results (fn [page & args]
+ (apply orig-exec (wrap-result page) args))]
(dotimes [_ 10]
(reset! page-counter 3)
(binding [bigquery/*page-size* 100 ; small pages so there are several
@@ -1224,10 +1224,10 @@
:db_id (u/the-id db)}]
(let [db-id (u/the-id db)
call-count (atom 0)
- orig-fn @#'bigquery/convert-dataset-id-to-filters!]
- (with-redefs [bigquery/convert-dataset-id-to-filters! (fn [database dataset-id]
- (swap! call-count inc)
- (orig-fn database dataset-id))]
+ orig-fn (mt/original-fn #'bigquery/convert-dataset-id-to-filters!)]
+ (mt/with-dynamic-fn-redefs [bigquery/convert-dataset-id-to-filters! (fn [database dataset-id]
+ (swap! call-count inc)
+ (orig-fn database dataset-id))]
;; fetch the Database from app DB a few more times to ensure the normalization changes are only called once
(doseq [_ (range 5)]
(is (nil? (get-in (t2/select-one :model/Database :id db-id) [:details :dataset-id]))))
diff --git a/modules/drivers/clickhouse/test/metabase/driver/clickhouse_test.clj b/modules/drivers/clickhouse/test/metabase/driver/clickhouse_test.clj
index ff7c0ca0497..998ebef9350 100644
--- a/modules/drivers/clickhouse/test/metabase/driver/clickhouse_test.clj
+++ b/modules/drivers/clickhouse/test/metabase/driver/clickhouse_test.clj
@@ -400,9 +400,9 @@
(deftest ^:synchronized csv-upload-and-sync-test
(testing "ClickHouse CSV uploads work correctly when cloud mode is enabled"
(mt/test-driver :clickhouse
- (with-redefs [clickhouse-version/dbms-version (constantly {:cloud true
- :version "24.8.1"
- :semantic-version {:major 24 :minor 8}})]
+ (mt/with-dynamic-fn-redefs [clickhouse-version/dbms-version (constantly {:cloud true
+ :version "24.8.1"
+ :semantic-version {:major 24 :minor 8}})]
(let [details (-> (mt/dbdef->connection-details :clickhouse :db {:database-name "uploads_schema"})
(assoc :enable-multiple-db false))
conn-spec (sql-jdbc.conn/connection-details->spec :clickhouse details)]
diff --git a/modules/drivers/druid/test/metabase/driver/druid/client_test.clj b/modules/drivers/druid/test/metabase/driver/druid/client_test.clj
index e4ba8327fc0..4bd715a88b0 100644
--- a/modules/drivers/druid/test/metabase/driver/druid/client_test.clj
+++ b/modules/drivers/druid/test/metabase/driver/druid/client_test.clj
@@ -37,9 +37,9 @@
(tqpt/with-flattened-dbdef
(let [query (mt/mbql-query checkins)
executed-query (atom nil)]
- (with-redefs [druid.client/do-query-with-cancellation (fn [_chan _details query]
- (reset! executed-query query)
- [])]
+ (mt/with-dynamic-fn-redefs [druid.client/do-query-with-cancellation (fn [_chan _details query]
+ (reset! executed-query query)
+ [])]
(qp/process-query query)
(is (partial= {:context {:timeout driver.settings/*query-timeout-ms*}}
@executed-query)))))))
diff --git a/modules/drivers/mongo/test/metabase/driver/mongo/execute_test.clj b/modules/drivers/mongo/test/metabase/driver/mongo/execute_test.clj
index ef2e8f83a1c..ec8b1723d54 100644
--- a/modules/drivers/mongo/test/metabase/driver/mongo/execute_test.clj
+++ b/modules/drivers/mongo/test/metabase/driver/mongo/execute_test.clj
@@ -107,16 +107,16 @@
:query (str "[{\"$addFields\": {}}\n"
" {\"$limit\":1}]")}}}]
(mt/with-temporary-setting-values [enable-query-caching true]
- (let [orig-freeze! @#'middleware.cache.impl/freeze!
+ (let [orig-freeze! (mt/original-fn #'middleware.cache.impl/freeze!)
freeze-started (atom false)
thrown-data (atom [])]
- (with-redefs [middleware.cache.impl/freeze! (fn [& args]
- (reset! freeze-started true)
- (try
- (apply orig-freeze! args)
- (catch Throwable t
- (swap! thrown-data conj t)
- (throw t))))]
+ (mt/with-dynamic-fn-redefs [middleware.cache.impl/freeze! (fn [& args]
+ (reset! freeze-started true)
+ (try
+ (apply orig-freeze! args)
+ (catch Throwable t
+ (swap! thrown-data conj t)
+ (throw t))))]
(let [model-based-query (-> (mt/mbql-query orders {:source-table (str "card__" (:id c))})
(update :cache_strategy assoc
;; Enable caching for current query
diff --git a/modules/drivers/mongo/test/metabase/driver/mongo/query_processor_test.clj b/modules/drivers/mongo/test/metabase/driver/mongo/query_processor_test.clj
index a57c8abb90a..b9c7f51016f 100644
--- a/modules/drivers/mongo/test/metabase/driver/mongo/query_processor_test.clj
+++ b/modules/drivers/mongo/test/metabase/driver/mongo/query_processor_test.clj
@@ -435,7 +435,7 @@
(mt/test-driver :mongo
(mt/with-metadata-provider (mt/id)
(testing "Mixed integer and date arithmetic works with Mongo 5+"
- (with-redefs [mongo.qp/get-mongo-version (constantly {:version "5.2.13", :semantic-version [5 2 13]})]
+ (mt/with-dynamic-fn-redefs [mongo.qp/get-mongo-version (constantly {:version "5.2.13", :semantic-version [5 2 13]})]
(mt/with-clock #t "2022-06-21T15:36:00+02:00[Europe/Berlin]"
(is (= {"$expr"
{"$lt"
@@ -466,7 +466,7 @@
(mt/test-driver :mongo
(mt/with-metadata-provider (mt/id)
(testing "Date arithmetic fails with Mongo 4-"
- (with-redefs [mongo.qp/get-mongo-version (constantly {:version "4", :semantic-version [4]})]
+ (mt/with-dynamic-fn-redefs [mongo.qp/get-mongo-version (constantly {:version "4", :semantic-version [4]})]
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
#"Date arithmetic not supported in versions before 5"
diff --git a/modules/drivers/mongo/test/metabase/driver/mongo_test.clj b/modules/drivers/mongo/test/metabase/driver/mongo_test.clj
index e176fc9434a..8dfeb4743ac 100644
--- a/modules/drivers/mongo/test/metabase/driver/mongo_test.clj
+++ b/modules/drivers/mongo/test/metabase/driver/mongo_test.clj
@@ -837,14 +837,14 @@
(deftest strange-versionArray-test
(mt/test-driver :mongo
(testing "Negative values in versionArray are ignored (#29678)"
- (with-redefs [mongo.util/run-command (constantly {"version" "4.0.28-23"
- "versionArray" [4 0 29 -100]})]
+ (mt/with-dynamic-fn-redefs [mongo.util/run-command (constantly {"version" "4.0.28-23"
+ "versionArray" [4 0 29 -100]})]
(is (= {:version "4.0.28-23"
:semantic-version [4 0 29]}
(driver/dbms-version :mongo (mt/db))))))
(testing "Any values after rubbish in versionArray are ignored"
- (with-redefs [mongo.util/run-command (constantly {"version" "4.0.28-23"
- "versionArray" [4 0 "NaN" 29]})]
+ (mt/with-dynamic-fn-redefs [mongo.util/run-command (constantly {"version" "4.0.28-23"
+ "versionArray" [4 0 "NaN" 29]})]
(is (= {:version "4.0.28-23"
:semantic-version [4 0]}
(driver/dbms-version :mongo (mt/db))))))))
@@ -1034,7 +1034,7 @@
:mongo
(testing "Ensure _id is present in results"
;; Gist: Limit is set to 2 and there, other fields' names that precede the _id when sorted
- (with-redefs [driver.settings/sync-leaf-fields-limit (constantly 2)]
+ (mt/with-dynamic-fn-redefs [driver.settings/sync-leaf-fields-limit (constantly 2)]
(with-describe-table-for-sample
[{"_id" {"$toObjectId" (org.bson.types.ObjectId.)}
"__a" 1
@@ -1128,7 +1128,7 @@
{:path "a.b.c.d.e.f.g", :type "array", :indices [1 0 0 0 0 0 0]}
{:path "a.b.c.d.e.f.i", :type "int", :indices [1 0 0 0 0 0 1]}
{:path "a.b.c.d.e.f.h", :type "null", :indices [1 0 0 0 0 0 0]}]]]]
- (with-redefs [driver.settings/sync-leaf-fields-limit (constantly limit)]
+ (mt/with-dynamic-fn-redefs [driver.settings/sync-leaf-fields-limit (constantly limit)]
(with-describe-table-for-sample
[{"_id" {"$toObjectId" (org.bson.types.ObjectId.)}
"a" {"b" {"c" {"d" {"e" {"f" {"g" [3 2 1]}}}}}}}
diff --git a/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj b/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj
index 11f05055b62..69262eff91d 100644
--- a/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj
+++ b/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj
@@ -189,7 +189,7 @@
(deftest ddl-statements-test
(testing "make sure we didn't break the code that is used to generate DDL statements when we add new test datasets"
- (with-redefs [test.data.snowflake/qualified-db-name (constantly "v4_test-data")]
+ (mt/with-dynamic-fn-redefs [test.data.snowflake/qualified-db-name (constantly "v4_test-data")]
(testing "Create DB DDL statements"
(is (= "CREATE DATABASE IF NOT EXISTS \"v4_test-data\";"
(sql.tx/create-db-sql :snowflake (mt/get-dataset-definition defs/test-data)))))
@@ -1467,7 +1467,7 @@
(let [{schema :schema, table-name :name} (t2/select-one :model/Table (mt/id :checkins))]
(qp.store/with-metadata-provider (mt/id)
(testing "checking select privilege defaults to allow on timeout (#56737)"
- (with-redefs [sql-jdbc.describe-database/simple-select-probe-query (constantly ["SELECT SYSTEM$WAIT(3, 'SECONDS')"])]
+ (mt/with-dynamic-fn-redefs [sql-jdbc.describe-database/simple-select-probe-query (constantly ["SELECT SYSTEM$WAIT(3, 'SECONDS')"])]
(binding [sql-jdbc.describe-database/*select-probe-query-timeout-seconds* 1]
(sql-jdbc.execute/do-with-connection-with-options
driver/*driver*
diff --git a/test/metabase/pulse/task/send_pulses_test.clj b/test/metabase/pulse/task/send_pulses_test.clj
index c8decaa136c..2cf44663516 100644
--- a/test/metabase/pulse/task/send_pulses_test.clj
+++ b/test/metabase/pulse/task/send_pulses_test.clj
@@ -204,6 +204,7 @@
(pulse-channel-test/with-send-pulse-setup!
(mt/with-model-cleanup [:model/Pulse]
(let [sent-channel-ids (atom #{})]
+ ;; with-redefs (cross-thread): quartz scheduler threads don't inherit *local-redefs*
#_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}
(with-redefs [;; run the job every second
u.cron/schedule-map->cron-string (constantly "* * * 1/1 * ? *")