The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Improve with-dynamic-fn-redefs linting + use it more (#73140)
Chris Truter0d3b96d8a20d
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.ednindex 6f67888c4b3..4654efeccf1 100644--- a/.clj-kondo/config.edn+++ b/.clj-kondo/config.edn@@ -69,6 +69,7 @@:metabase/modules {:level :warning} ; more config in `.clj-kondo/config/modules/config.edn`:metabase/namespace-name {:level :warning}:metabase/no-jsqlparser-imports {:level :warning}+ :metabase/prefer-with-dynamic-fn-redefs {:level :warning}:metabase/toucan-model-ns {:level :warning}:metabase/require-shape-checker {:level :warning}:metabase/tests-must-live-in-known-modules {:level :warning}@@ -310,8 +311,7 @@metabase-enterprise.transforms.interface/execute! {:message "Use metabase-enterprise.transforms.execute/execute! instead of metabase-enterprise.transforms.interface/execute!"}next.jdbc/active-tx? {:message "Use metabase.app-db.core/in-transaction? to see if we are in a transaction"}toucan2.core/debug {:message "Don't commit code using t2/debug"}- toucan2.tools.debug/debug {:message "Don't commit code using t2/debug"}- }+ toucan2.tools.debug/debug {:message "Don't commit code using t2/debug"}}:discouraged-namespace{camel-snake-kebab.core {:message "CSK is not Turkish-safe, use the versions in metabase.util instead."}@@ -537,6 +537,7 @@clojure.core/ns hooks.clojure.core.ns/lint-nsclojure.core/require hooks.clojure.core.require/lint-requireclojure.core/requiring-resolve hooks.clojure.core.require/lint-requiring-resolve+ clojure.core/with-redefs hooks.clojure.core.with-redefs/lint-with-redefsclojure.core/- hooks.metabase.util.timing/discourage-millis-durationclojure.test/deftest hooks.clojure.test/deftestclojure.test/is hooks.clojure.test/is@@ -784,7 +785,14 @@:name general-qp-and-driver-test-namespaces}{:pattern "(?:^mage.*)"- :name mage-namespaces}]+ :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}]:config-in-ns{test-namespaces@@ -801,9 +809,21 @@metabase.lib.convert/->legacy-MBQL {:level :off}metabase.lib.core/->legacy-MBQL {:level :off}}}}+ ;; .cljc tests run in both Clojure and ClojureScript — `with-dynamic-fn-redefs` is JVM-only,+ ;; so leave these alone.+ metabase.lib.aggregation-test+ {:linters {:metabase/prefer-with-dynamic-fn-redefs {:level :off}}}+ 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}+ :metabase/prefer-with-dynamic-fn-redefs {:level :off}:metabase/validate-defendpoint-has-response-schema {:level :warning}:metabase/validate-escaped-single-quotes-in-i18n {:level :warning}:metabase/validate-string-or-str-args-to-i18n {:level :warning}diff --git a/.clj-kondo/src/hooks/clojure/core/with_redefs.clj b/.clj-kondo/src/hooks/clojure/core/with_redefs.cljnew file mode 100644index 00000000000..2f711cc6bdc--- /dev/null+++ b/.clj-kondo/src/hooks/clojure/core/with_redefs.clj@@ -0,0 +1,72 @@+(ns hooks.clojure.core.with-redefs+ (:require+ [clj-kondo.hooks-api :as hooks]))++(defn- defn-arity?+ "Look up `var-sym` in `analysis` (the result of `hooks/ns-analysis`, keyed by language)+ and return true iff kondo recorded a non-empty arity for it. clj-kondo only emits+ arities for `defn`-style fns — `defmulti` and plain `def` have neither `:fixed-arities`+ nor `:varargs-min-arity`, so the presence of either is a clean, dynamic signal that+ the var is a regular function we can safely nudge.++ We coerce to boolean and `seq`-check `:fixed-arities` so a hypothetical empty set+ doesn't leak through as truthy. The smoke test in `with-redefs-test` empirically+ verifies the \"arities iff `defn`\" invariant against a real `clj-kondo` run — if a+ future kondo release starts emitting arities for `defmulti` it will fail there+ rather than silently producing wrong nudges."+ [analysis var-sym]+ (boolean+ (some (fn [lang-vars]+ (when-let [v (get lang-vars var-sym)]+ (or (seq (:fixed-arities v))+ (:varargs-min-arity v))))+ (vals analysis))))++(defn- safely-nudgeable-lhs?+ "Is this LHS a regular function (defn) according to kondo's analysis?++ Returns false for:+ - unresolved symbols (e.g. namespace alias not in scope, ns not yet analysed)+ - vars defined by `defmulti` (no arity recorded)+ - vars defined by `def` (no arity recorded)+ Returns true only when kondo has arity info for the var, which is the case for `defn`+ and `defn-`. This means the nudge fires only when we're sure the target is a plain+ function — no manual list of multimethod targets to maintain.++ We deliberately bias toward false (skip the nudge) when uncertain. The cost of a missed+ nudge is small; the cost of a wrong nudge is a runtime error from+ `with-dynamic-fn-redefs` refusing to proxy a multimethod."+ [lhs]+ (and (hooks/token-node? lhs)+ (symbol? (hooks/sexpr lhs))+ (let [resolved (hooks/resolve {:name (hooks/sexpr lhs)})+ ns-sym (:ns resolved)]+ (and (symbol? ns-sym) ; not :clj-kondo/unknown-namespace+ (defn-arity? (hooks/ns-analysis ns-sym) (:name resolved))))))++(defn lint-with-redefs+ "Suggest `with-dynamic-fn-redefs` when every LHS is known to be a `defn`-style var.++ We don't gate on the RHS — `with-dynamic-fn-redefs` accepts any `IFn` replacement+ (fns, keywords, colls), and the LHS check alone is enough to know the form is+ migratable as a whole. The `every?` keeps it whole-form: mixed bindings that include+ a non-defn LHS (defmulti, plain `def`, unresolved) can't be split usefully — the+ leftover `with-redefs` still does a global root-swap, so the form remains thread-unsafe.++ The LHS check uses kondo's own analysis cache rather than a hand-maintained list of+ multimethod names — adding a new `defmulti` doesn't require touching this hook."+ [{:keys [node]}]+ (let [[_with-redefs bindings-vec] (:children node)]+ (when (hooks/vector-node? bindings-vec)+ (let [pairs (partition-all 2 (:children bindings-vec))]+ (when (and (seq pairs)+ (every? (fn [[lhs rhs]]+ (and rhs (safely-nudgeable-lhs? lhs)))+ pairs))+ (hooks/reg-finding!+ (assoc (meta node)+ :message (str "Every binding here redefines a defn-style var — prefer "+ "metabase.test/with-dynamic-fn-redefs for thread-safe "+ "redefs. [:metabase/prefer-with-dynamic-fn-redefs]")+ :type :metabase/prefer-with-dynamic-fn-redefs))))))+ {:node node})diff --git a/.clj-kondo/test/hooks/clojure/core/with_redefs_test.clj b/.clj-kondo/test/hooks/clojure/core/with_redefs_test.cljnew file mode 100644index 00000000000..b6778106ace--- /dev/null+++ b/.clj-kondo/test/hooks/clojure/core/with_redefs_test.clj@@ -0,0 +1,152 @@+(ns hooks.clojure.core.with-redefs-test+ (:require+ [clj-kondo.core :as kondo]+ [clj-kondo.hooks-api :as hooks]+ [clj-kondo.impl.utils]+ [clojure.java.io :as io]+ [clojure.test :refer :all]+ [hooks.clojure.core.with-redefs]))++;;; The new hook delegates the "is this LHS a regular defn?" decision to clj-kondo's own+;;; analysis cache via [[hooks/resolve]] and [[hooks/ns-analysis]]. In unit tests we have+;;; no cache, so we stub those calls. The mapping below describes what each stubbed name+;;; should pretend to be.++(def ^:private stub-vars+ "Map of unqualified-name → kondo-style var-definition. Names not in the map are treated+ as `:clj-kondo/unknown-namespace` (unresolved). A `:fixed-arities` (or+ `:varargs-min-arity`) entry means \"this is a `defn`\" and is the only thing that lets+ the nudge fire."+ '{plain-fn {:ns example.ns :name plain-fn :fixed-arities #{1}}+ plain-fn-2 {:ns example.ns :name plain-fn-2 :fixed-arities #{0}}+ a-multimethod {:ns example.ns :name a-multimethod} ; defmulti — no arities+ can-read? {:ns example.ns :name can-read?} ; defmulti+ can-query? {:ns example.ns :name can-query?} ; defmulti+ a-value {:ns example.ns :name a-value}}) ; (def a-value 42) — no arities++(defn- stub-resolve [{nm :name}]+ (when (symbol? nm)+ (let [bare (symbol (name nm))]+ (if (contains? stub-vars bare)+ {:ns 'example.ns :name bare}+ {:ns :clj-kondo/unknown-namespace :name bare}))))++(defn- stub-ns-analysis [_ns-sym]+ ;; All stubbed vars live in `example.ns` for simplicity.+ {:clj stub-vars})++(defn- lint+ "Run the hook on the given source. Pass a string to preserve reader-macro literals like+ `#(...)` (whose `:fn` node tag is distinct from a regular list); pass a quoted form+ for the common case where exact node shape doesn't matter. The optional+ `analysis-fn` stub overrides `hooks/ns-analysis` for tests that want to simulate a+ cache miss or other non-default cache state."+ ([src] (lint src stub-ns-analysis))+ ([src analysis-fn]+ (binding [clj-kondo.impl.utils/*ctx* {:config {:linters {:metabase/prefer-with-dynamic-fn-redefs {:level :warning}}}+ :ignores (atom nil)+ :findings (atom [])+ :namespaces (atom {})}]+ (with-redefs [hooks/resolve stub-resolve+ hooks/ns-analysis analysis-fn]+ (hooks.clojure.core.with-redefs/lint-with-redefs+ {:node (hooks/parse-string (if (string? src) src (pr-str src)))}))+ @(:findings clj-kondo.impl.utils/*ctx*))))++(deftest ^:synchronized flags-when-every-lhs-is-defn-test+ (testing "RHS shape doesn't matter — once every LHS resolves to a defn, the form is a+ migration candidate regardless of what's on the right. We deliberately stick+ to `IFn`-valued shapes here (fns, keywords, colls) — pairing a fn-var LHS+ with a non-`IFn` value (`42`) would be a weird shape callers wouldn't realistically+ write, and `with-dynamic-fn-redefs` would throw at proxy time anyway."+ (doseq [rhs ['(fn [x] x)+ '(constantly 42)+ '(partial + 1)+ '(comp inc dec)+ 'identity ; bare symbol resolving to an IFn+ '(foo/constantly 42) ; namespaced lookalike — no longer special-cased+ :a-key ; keyword (IFn)+ {:a 1} ; map (IFn)+ [1 2 3]]] ; vector (IFn)+ (is (=? [{:type :metabase/prefer-with-dynamic-fn-redefs}]+ (lint (list 'with-redefs ['plain-fn rhs] :body)))+ (str "expected nudge for RHS: " (pr-str rhs)))))+ (testing "reader-macro `#(...)` literal — passed as a string so it parses as a+ `:fn`-tagged node, not the post-expansion `(fn* …)` list. Still works because+ it's just one more shape the LHS-only rule treats uniformly."+ (is (=? [{:type :metabase/prefer-with-dynamic-fn-redefs}]+ (lint "(with-redefs [plain-fn #(inc %)] (plain-fn 1))"))))+ (testing "multiple bindings, every LHS is a defn"+ (is (=? [{:type :metabase/prefer-with-dynamic-fn-redefs}]+ (lint '(with-redefs [plain-fn (constantly 1)+ plain-fn-2 (fn [] 2)]+ (plain-fn)))))))++(deftest ^:synchronized skips-multimethod-and-value-targets-test+ (testing "defmulti — no arity in analysis, so don't nudge"+ (is (= [] (lint '(with-redefs [a-multimethod (fn [& _] nil)] :body))))+ (is (= [] (lint '(with-redefs [can-read? (constantly true)] :body))))+ (is (= [] (lint '(with-redefs [can-query? (constantly false)] :body)))))+ (testing "plain `def` value also has no arity — don't nudge"+ (is (= [] (lint '(with-redefs [a-value (fn [] 1)] :body)))))+ (testing "any unresolved symbol skips the nudge — we never know what it is"+ (is (= [] (lint '(with-redefs [unknown.ns/something (fn [& _] nil)] :body)))))+ (testing "empty analysis (cache miss for the resolved ns) → skip the nudge"+ (is (= [] (lint '(with-redefs [plain-fn (fn [x] x)] :body)+ (constantly {})))))+ (testing "mixed bindings — even one non-defn LHS suppresses the nudge"+ (is (= [] (lint '(with-redefs [plain-fn (fn [x] x)+ a-multimethod (fn [& _] nil)]+ :body))))))++(defn- spit-fixture! [^java.io.File f content]+ (.mkdirs (.getParentFile f))+ (spit f content))++(defn- delete-tree! [^java.io.File f]+ (when (.isDirectory f)+ (run! delete-tree! (.listFiles f)))+ (.delete f))++(defn- run-kondo-twice+ "Lint `src` first to populate `cache-dir` (mirroring the real `kondo --lint src test`+ pipeline), then lint `test-file` against that cache and return its findings. The+ two-pass shape is required because the hook reads its decisions from the cache, which+ is only written *after* a file is analysed."+ [cache-dir src-file test-file]+ (kondo/run! {:lint [(.getPath src-file)] :cache-dir cache-dir :config-dir ".clj-kondo"})+ (:findings (kondo/run! {:lint [(.getPath test-file)] :cache-dir cache-dir :config-dir ".clj-kondo"})))++(deftest ^:synchronized integration-arities-iff-defn-smoke-test+ (testing "real kondo run validates the load-bearing invariant: only `defn`-style vars+ get arities recorded — `defmulti` and plain `def` do not. If a future kondo+ release breaks this, the smoke test fails here rather than the hook silently+ producing wrong nudges."+ (let [tmp-dir (.toFile (java.nio.file.Files/createTempDirectory+ "with-redefs-smoke" (into-array java.nio.file.attribute.FileAttribute [])))+ cache-dir (str tmp-dir "/cache")+ src (io/file tmp-dir "smoke_fixture.clj")+ tst (io/file tmp-dir "smoke_fixture_test.clj")]+ (try+ (spit-fixture! src "(ns smoke-fixture)+(defmulti the-multi {:arglists '([x])} (fn [x] x))+(defn the-defn [x] x)+(def the-value 42)+")+ (spit-fixture! tst "(ns smoke-fixture-test+ (:require [smoke-fixture :as f]))+(with-redefs [f/the-multi (constantly nil)] :a)+(with-redefs [f/the-defn (constantly nil)] :b)+(with-redefs [f/the-value (constantly nil)] :c)+")+ (let [findings (run-kondo-twice cache-dir src tst)+ nudges (filter #(= :metabase/prefer-with-dynamic-fn-redefs (:type %)) findings)+ nudge-rows (set (map :row nudges))]+ ;; Row 3 = the-multi, row 4 = the-defn, row 5 = the-value (matches the+ ;; with-redefs lines in the test fixture above).+ (testing "the defn binding gets nudged"+ (is (contains? nudge-rows 4)))+ (testing "the defmulti and def bindings do not get nudged"+ (is (not (contains? nudge-rows 3)))+ (is (not (contains? nudge-rows 5)))))+ (finally (delete-tree! tmp-dir))))))diff --git a/test/metabase/actions/actions_test.clj b/test/metabase/actions/actions_test.cljindex 9360332ceea..f99d027409b 100644--- a/test/metabase/actions/actions_test.clj+++ b/test/metabase/actions/actions_test.clj@@ -845,11 +845,11 @@(mt/with-actions-test-data-and-actions-enabled(let [db-id (mt/id)write-cache-key [db-id :write-data]]- (with-redefs [driver.conn/effective-connection-type- (fn [_database]- (if (= driver.conn/*connection-type* :write-data)- :write-data- :default))]+ (mt/with-dynamic-fn-redefs [driver.conn/effective-connection-type+ (fn [_database]+ (if (= driver.conn/*connection-type* :write-data)+ :write-data+ :default))](try(sql-jdbc.conn/invalidate-pool-for-db! (mt/db))(testing "write pool does not exist before action execution"diff --git a/test/metabase/actions/execution_write_pool_test.clj b/test/metabase/actions/execution_write_pool_test.cljindex e81dfde0781..6ceaf074006 100644--- a/test/metabase/actions/execution_write_pool_test.clj+++ b/test/metabase/actions/execution_write_pool_test.clj@@ -13,11 +13,11 @@(mt/with-actions-test-data-and-actions-enabled(let [db-id (mt/id)write-cache-key [db-id :write-data]]- (with-redefs [driver.conn/effective-connection-type- (fn [_database]- (if (= driver.conn/*connection-type* :write-data)- :write-data- :default))]+ (mt/with-dynamic-fn-redefs [driver.conn/effective-connection-type+ (fn [_database]+ (if (= driver.conn/*connection-type* :write-data)+ :write-data+ :default))](try(sql-jdbc.conn/invalidate-pool-for-db! (mt/db))(testing "write pool does not exist before query action execution"diff --git a/test/metabase/activity_feed/models/recent_views_test.clj b/test/metabase/activity_feed/models/recent_views_test.cljindex ca167159b4d..444c1e64e33 100644--- a/test/metabase/activity_feed/models/recent_views_test.clj+++ b/test/metabase/activity_feed/models/recent_views_test.clj@@ -491,7 +491,7 @@(count model-ids) model recent-views/*recent-views-stored-per-user-per-model*)(is (= 2 (count (filter (comp #{out-model} :model)(mt/with-test-user :rasta- (with-redefs [data-perms/user-has-permission-for-table? (constantly true)]+ (mt/with-dynamic-fn-redefs [data-perms/user-has-permission-for-table? (constantly true)](recent-views (mt/user->id :rasta))))))))))(is(= {:card recent-views/*recent-views-stored-per-user-per-model*,@@ -501,7 +501,7 @@:table recent-views/*recent-views-stored-per-user-per-model*}(frequencies (map :model(mt/with-test-user :rasta- (with-redefs [data-perms/user-has-permission-for-table? (constantly true)]+ (mt/with-dynamic-fn-redefs [data-perms/user-has-permission-for-table? (constantly true)](recent-views (mt/user->id :rasta)))))))"After inserting 3 views of each model, we should have 2 views PER each model.")))))@@ -541,7 +541,7 @@(with-redefs [mi/can-read? (constantly true)data-perms/user-has-permission-for-table? (constantly true)](let [freqs (frequencies (map :model- (with-redefs [data-perms/user-has-permission-for-table? (constantly true)]+ (mt/with-dynamic-fn-redefs [data-perms/user-has-permission-for-table? (constantly true)](mt/with-test-user :rasta (recent-views (mt/user->id :rasta))))))](is (= 3 (:card freqs)))(is (= 3 (:dataset freqs)))diff --git a/test/metabase/agent_lib/runtime/fields_test.clj b/test/metabase/agent_lib/runtime/fields_test.cljindex 7f2e82905a0..21c4fa71c98 100644--- a/test/metabase/agent_lib/runtime/fields_test.clj+++ b/test/metabase/agent_lib/runtime/fields_test.clj@@ -2,7 +2,8 @@(:require[clojure.test :refer [deftest is]][metabase.agent-lib.mbql-integration :as mbql]- [metabase.agent-lib.runtime.fields :as runtime.fields]))+ [metabase.agent-lib.runtime.fields :as runtime.fields]+ [metabase.test :as mt]))(deftest resolve-field-in-query-prefers-chained-lineage-over-raw-exact-match-test(let [raw-field {:id 300 :table-id 30 :name "name" :base-type :type/Text}@@ -10,8 +11,8 @@source-column {:id 200 :table-id 20 :name "customer_id" :base-type :type/Integer}fields-by-id {200 {:id 200 :table-id 20 :fk-target-field-id 301}301 {:id 301 :table-id 30}}- resolved-field (with-redefs [mbql/current-query-field-candidates- (constantly [raw-exact source-column])]+ resolved-field (mt/with-dynamic-fn-redefs [mbql/current-query-field-candidates+ (constantly [raw-exact source-column])](runtime.fields/resolve-field-in-query fields-by-id ::query raw-field))](is (= 300 (:id resolved-field)))(is (= 200 (:fk-field-id resolved-field)))@@ -29,8 +30,8 @@2499 {:id 2499 :table-id 133 :name "id"}2488 {:id 2488 :table-id 133 :name "customer_id" :fk-target-field-id 2456}2456 {:id 2456 :table-id 127 :name "id"}}- resolved-field (with-redefs [mbql/current-query-field-candidates- (constantly [source-column])]+ resolved-field (mt/with-dynamic-fn-redefs [mbql/current-query-field-candidates+ (constantly [source-column])](runtime.fields/resolve-field-in-query fields-by-id ::query raw-field))](is (= 2455 (:id resolved-field)))(is (= 2488 (:fk-field-id resolved-field)))@@ -48,8 +49,8 @@:source-field-name "order_id"}fields-by-id {2488 {:id 2488 :table-id 133 :fk-target-field-id 2456}2456 {:id 2456 :table-id 127}}- resolved-field (with-redefs [mbql/current-query-field-candidates- (constantly [source-column])]+ resolved-field (mt/with-dynamic-fn-redefs [mbql/current-query-field-candidates+ (constantly [source-column])](runtime.fields/resolve-field-in-query fields-by-id ::query raw-field))](is (= 2455 (:id resolved-field)))(is (= 2488 (:fk-field-id resolved-field)))@@ -69,8 +70,8 @@2499 {:id 2499 :table-id 133}2488 {:id 2488 :table-id 133 :fk-target-field-id 2456}2456 {:id 2456 :table-id 127}}- resolved-field (with-redefs [mbql/current-query-field-candidates- (constantly [source-column])]+ resolved-field (mt/with-dynamic-fn-redefs [mbql/current-query-field-candidates+ (constantly [source-column])](runtime.fields/resolve-field-in-query fields-by-id ::query raw-field))](is (= "order__via__order_id" (:fk-join-alias resolved-field)))(is (= "order__via__order_id" (:lib/original-fk-join-alias resolved-field)))))@@ -94,8 +95,8 @@2499 {:id 2499 :table-id 133 :name "id"}2488 {:id 2488 :table-id 133 :name "customer_id" :fk-target-field-id 2456}2456 {:id 2456 :table-id 127 :name "id"}}- resolved-field (with-redefs [mbql/current-query-field-candidates- (constantly [exact-partial source-column])]+ resolved-field (mt/with-dynamic-fn-redefs [mbql/current-query-field-candidates+ (constantly [exact-partial source-column])](runtime.fields/resolve-field-in-query fields-by-id ::query raw-field))](is (= 2455 (:id resolved-field)))(is (= 2488 (:fk-field-id resolved-field)))@@ -112,8 +113,8 @@:base-type :type/Decimal:effective-type :type/Decimal:lib/source :source/previous-stage}- resolved-field (with-redefs [mbql/current-query-field-candidates- (constantly [raw-exact previous-stage])]+ resolved-field (mt/with-dynamic-fn-redefs [mbql/current-query-field-candidates+ (constantly [raw-exact previous-stage])](runtime.fields/resolve-field-in-query {} ::query raw-field))](is (= previous-stage resolved-field))))@@ -127,8 +128,8 @@:base-type :type/Text:effective-type :type/Text:lib/source :source/previous-stage}- resolved-field (with-redefs [mbql/current-query-field-candidates- (constantly [previous-event-uri previous-name])]+ resolved-field (mt/with-dynamic-fn-redefs [mbql/current-query-field-candidates+ (constantly [previous-event-uri previous-name])](runtime.fields/resolve-field-in-query {} ::query raw-field))](is (= previous-name resolved-field))))@@ -140,8 +141,8 @@:lib/source :source/previous-stage}](is (thrown-with-msg? clojure.lang.ExceptionInfo#"not available in the current query stage"- (with-redefs [mbql/current-query-field-candidates- (constantly [previous-stage])]+ (mt/with-dynamic-fn-redefs [mbql/current-query-field-candidates+ (constantly [previous-stage])](runtime.fields/resolve-field-in-query {} ::query raw-field))))))(deftest unavailable-field-error-enumerates-available-fields-testdiff --git a/test/metabase/analytics/settings_test.clj b/test/metabase/analytics/settings_test.cljindex 586ea768f63..fe8e3702e39 100644--- a/test/metabase/analytics/settings_test.clj+++ b/test/metabase/analytics/settings_test.clj@@ -13,7 +13,7 @@(try(testing "Instance creation timestamp is set only once when setting is first fetched"(t2/delete! :model/Setting :key "instance-creation")- (with-redefs [analytics.settings/first-user-creation (constantly nil)]+ (mt/with-dynamic-fn-redefs [analytics.settings/first-user-creation (constantly nil)](let [first-value (analytics.settings/instance-creation)](Thread/sleep 10) ;; short sleep since java.time.Instant is not necessarily monotonic(is (= first-valuediff --git a/test/metabase/analytics/snowplow_test.clj b/test/metabase/analytics/snowplow_test.cljindex d80d6cf0062..ac503bbad18 100644--- a/test/metabase/analytics/snowplow_test.clj+++ b/test/metabase/analytics/snowplow_test.clj@@ -53,7 +53,7 @@anon-tracking-enabled true](binding [*snowplow-collector* (atom [])](let [collector *snowplow-collector*] ;; get a reference to the atom- (with-redefs [snowplow/track-event-impl! (partial fake-track-event-impl! collector)]+ (mt/with-dynamic-fn-redefs [snowplow/track-event-impl! (partial fake-track-event-impl! collector)](f))))));;; TODO -- rename to `with-fake-snowplow-collector!` because this is not thread-safe and remove the Kondo ignore rule belowdiff --git a/test/metabase/analytics/stats_test.clj b/test/metabase/analytics/stats_test.cljindex 861670b7099..4c366d815cf 100644--- a/test/metabase/analytics/stats_test.clj+++ b/test/metabase/analytics/stats_test.clj@@ -88,8 +88,8 @@"250+" 5000))(deftest anonymous-usage-stats-test- (with-redefs [channel.settings/email-configured? (constantly false)- channel.settings/slack-configured? (constantly false)]+ (mt/with-dynamic-fn-redefs [channel.settings/email-configured? (constantly false)+ channel.settings/slack-configured? (constantly false)](mt/with-temporary-setting-values [site-name "Metabase"startup-time-millis 1234.0google-auth-enabled false@@ -126,8 +126,8 @@(deftest anonymous-usage-stats-test-ee-with-values-changed; some settings are behind the whitelabel feature flag(mt/with-premium-features #{:whitelabel}- (with-redefs [channel.settings/email-configured? (constantly false)- channel.settings/slack-configured? (constantly false)]+ (mt/with-dynamic-fn-redefs [channel.settings/email-configured? (constantly false)+ channel.settings/slack-configured? (constantly false)](mt/with-temporary-setting-values [site-name "My Company Analytics"startup-time-millis 1234.0google-auth-enabled false@@ -455,26 +455,26 @@(testing "csv-upload-available? currently detects upload availability based on the current MB version"(mt/with-temp [:model/Database _ {:engine :postgres}]- (with-redefs [config/current-major-version (constantly 46)- config/current-minor-version (constantly 0)]+ (mt/with-dynamic-fn-redefs [config/current-major-version (constantly 46)+ config/current-minor-version (constantly 0)](is (false? (@#'stats/csv-upload-available?))))- (with-redefs [config/current-major-version (constantly 47)- config/current-minor-version (constantly 1)]+ (mt/with-dynamic-fn-redefs [config/current-major-version (constantly 47)+ config/current-minor-version (constantly 1)](is (true? (@#'stats/csv-upload-available?))))))(mt/with-temp [:model/Database _ {:engine :redshift}]- (with-redefs [config/current-major-version (constantly 49)- config/current-minor-version (constantly 5)]+ (mt/with-dynamic-fn-redefs [config/current-major-version (constantly 49)+ config/current-minor-version (constantly 5)](is (false? (@#'stats/csv-upload-available?))))- (with-redefs [config/current-major-version (constantly 49)- config/current-minor-version (constantly 6)]+ (mt/with-dynamic-fn-redefs [config/current-major-version (constantly 49)+ config/current-minor-version (constantly 6)](is (true? (@#'stats/csv-upload-available?))))));; If we can't detect the MB version, return nil- (with-redefs [config/current-major-version (constantly nil)- config/current-minor-version (constantly nil)]+ (mt/with-dynamic-fn-redefs [config/current-major-version (constantly nil)+ config/current-minor-version (constantly nil)](is (false? (@#'stats/csv-upload-available?)))))(deftest starburst-legacy-test@@ -523,19 +523,19 @@(deftest deployment-model-test(testing "deployment model correctly reports cloud/docker/jar"- (with-redefs [premium-features.settings/is-hosted? (constantly true)]+ (mt/with-dynamic-fn-redefs [premium-features.settings/is-hosted? (constantly true)](is (= "cloud" (@#'stats/deployment-model))));; Lets just mock io/file to always return an existing (temp) file, to validate that we're doing a filesystem check;; to determine whether we're in a Docker container(mt/with-temp-file [mock-file](spit mock-file "Temp file!")- (with-redefs [premium-features.settings/is-hosted? (constantly false)- io/file (constantly (java.io.File. mock-file))]+ (mt/with-dynamic-fn-redefs [premium-features.settings/is-hosted? (constantly false)+ io/file (constantly (java.io.File. mock-file))](is (= "docker" (@#'stats/deployment-model)))))- (with-redefs [premium-features.settings/is-hosted? (constantly false)- stats/in-docker? (constantly false)]+ (mt/with-dynamic-fn-redefs [premium-features.settings/is-hosted? (constantly false)+ stats/in-docker? (constantly false)](is (= "jar" (@#'stats/deployment-model))))))(deftest no-features-enabled-but-not-available-testdiff --git a/test/metabase/api/downloads_exports_test.clj b/test/metabase/api/downloads_exports_test.cljindex bdcdaf3cd88..4f27595a78a 100644--- a/test/metabase/api/downloads_exports_test.clj+++ b/test/metabase/api/downloads_exports_test.clj@@ -1094,7 +1094,7 @@(deftest clean-errors-test(testing "Queries that error should not include visualization settings (metabase-private #233)"- (with-redefs [formatter/number-formatter (fn [& _args] (fn [_] (throw (Exception. "Test Exception"))))]+ (mt/with-dynamic-fn-redefs [formatter/number-formatter (fn [& _args] (fn [_] (throw (Exception. "Test Exception"))))](mt/with-temp [:model/Card {card-id :id} {:display :table:type :model:dataset_query {:database (mt/id)diff --git a/test/metabase/api_keys/api_test.clj b/test/metabase/api_keys/api_test.cljindex 90dbaa6f474..2bbc3ef0578 100644--- a/test/metabase/api_keys/api_test.clj+++ b/test/metabase/api_keys/api_test.clj@@ -50,9 +50,9 @@generated-keygenerated-key(api-key/generate-key)])]- (with-redefs [api-key/generate-key (fn [] (let [next-val (first @generated-keys)]- (swap! generated-keys next)- next-val))]+ (mt/with-dynamic-fn-redefs [api-key/generate-key (fn [] (let [next-val (first @generated-keys)]+ (swap! generated-keys next)+ next-val))];; put an API Key in the database with that key.(mt/with-temp [:model/ApiKey _ {::api-keys/unhashed-key generated-key:name "my cool name"@@ -70,7 +70,7 @@(mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Cool Friends"}](testing "We don't retry forever if prefix collision keeps happening"(let [generated-key (api-key/generate-key)]- (with-redefs [api-key/generate-key (constantly generated-key)]+ (mt/with-dynamic-fn-redefs [api-key/generate-key (constantly generated-key)](mt/with-temp [:model/ApiKey _ {::api-keys/unhashed-key generated-key:name "my cool name":user_id (mt/user->id :crowberto)diff --git a/test/metabase/app_db/custom_migrations_test.clj b/test/metabase/app_db/custom_migrations_test.cljindex 71bb0dc4c69..ccf6e05f51f 100644--- a/test/metabase/app_db/custom_migrations_test.clj+++ b/test/metabase/app_db/custom_migrations_test.clj@@ -1071,7 +1071,7 @@;; we're testing here, so let's override it to be a no-op. Other tests add DBs using the table name instead of;; model name, so they don't hit the post-insert hook, but here we're relying on the transformations being;; applied so we can't do that.- (with-redefs [database/set-new-database-permissions! (constantly nil)]+ (mt/with-dynamic-fn-redefs [database/set-new-database-permissions! (constantly nil)](impl/test-migrations ["v48.00-001" "v48.00-002"] [migrate!](let [default-db {:name "DB":engine "postgres"diff --git a/test/metabase/app_db/liquibase_test.clj b/test/metabase/app_db/liquibase_test.cljindex ee2c5bc8dad..dcee7c9bde9 100644--- a/test/metabase/app_db/liquibase_test.clj+++ b/test/metabase/app_db/liquibase_test.clj@@ -55,7 +55,7 @@(mt/test-drivers #{:h2 :mysql :postgres}(mt/with-temp-empty-app-db [conn driver/*driver*];; fake a db where we ran all the migrations, including the legacy ones- (with-redefs [liquibase/decide-liquibase-file (fn [& _args] @#'liquibase/changelog-legacy-file)]+ (mt/with-dynamic-fn-redefs [liquibase/decide-liquibase-file (fn [& _args] @#'liquibase/changelog-legacy-file)](liquibase/with-liquibase [liquibase conn](let [table-name (liquibase/changelog-table-name liquibase)](.update liquibase "")@@ -178,7 +178,7 @@(is (= actual-latest-applied-version (liquibase/latest-applied-major-version conn (.getDatabase liquibase)))))(testing "Cannot downgrade when there are changests from a newer version already ran which are not in the changelog file"- (with-redefs [liquibase/latest-applied-major-version (constantly (inc actual-latest-applied-version))]+ (mt/with-dynamic-fn-redefs [liquibase/latest-applied-major-version (constantly (inc actual-latest-applied-version))](is (thrown-with-msg? ExceptionInfo #"Cannot downgrade.*"(liquibase/rollback-major-version! conn liquibase false (dec actual-latest-available-version))))(testing "CAN downgrade if forced"diff --git a/test/metabase/app_db/schema_migrations_test.clj b/test/metabase/app_db/schema_migrations_test.cljindex 933e42d796b..cafc4e17498 100644--- a/test/metabase/app_db/schema_migrations_test.clj+++ b/test/metabase/app_db/schema_migrations_test.clj@@ -147,7 +147,7 @@;; Urgh. `collection/is-trash?` will select the Trash collection (cached) based on its `type`. But as of this;; migration, this `type` does not exist yet. Neither does the Trash collection though, so let's just ... make;; that so.- (with-redefs [collection/is-trash? (constantly false)]+ (mt/with-dynamic-fn-redefs [collection/is-trash? (constantly false)](testing "A personal Collection should get created_at set by to the date_joined from its owner"(is (= (t/offset-date-time #t "2022-10-20T02:09Z")(t/offset-date-time (t2/select-one-fn :created_at [:model/Collection :created_at] :id personal-collection-id)))))@@ -530,13 +530,13 @@(deftest ^:mb/old-migrations-test remove-collection-color-test(testing "Migration v48.00-019"(impl/test-migrations ["v48.00-019"] [migrate!]- (with-redefs [;; Urgh. `collection/is-trash?` will select the Trash collection (cached) based on its `type`. But as of this+ (mt/with-dynamic-fn-redefs [;; Urgh. `collection/is-trash?` will select the Trash collection (cached) based on its `type`. But as of this;; migration, this `type` does not exist yet. Neither does the Trash collection though, so let's just ... make;; that so.- collection/is-trash? (constantly false)+ collection/is-trash? (constantly false);; Also avoid loading sample content, because this test breaks the assumption that only the trash;; collection exists at the time of the migration- config/load-sample-content? (constantly false)]+ config/load-sample-content? (constantly false)](let [collection-id (first (t2/insert-returning-pks! (t2/table-name :model/Collection) {:name "Amazing collection":slug "amazing_collection":color "#509EE3"}))]@@ -2537,7 +2537,7 @@(deftest ^:mb/old-migrations-test trash-migrations-test(impl/test-migrations ["v50.2024-05-29T14:04:47" "v50.2024-05-29T18:42:15"] [migrate!]- (with-redefs [collection/is-trash? (constantly false)]+ (mt/with-dynamic-fn-redefs [collection/is-trash? (constantly false)](let [collection-id (t2/insert-returning-pk! (t2/table-name :model/Collection){:name "Silly Collection":archived true@@ -2568,7 +2568,7 @@(deftest ^:mb/old-migrations-test trash-migrations-make-archive-operation-ids-correctly(impl/test-migrations ["v50.2024-05-29T14:04:47" "v50.2024-05-29T18:42:15"] [migrate!]- (with-redefs [collection/is-trash? (constantly false)]+ (mt/with-dynamic-fn-redefs [collection/is-trash? (constantly false)](let [relevant-collection-ids (atom #{})parent-id (fn [id](:parent_id (t2/hydrate (t2/select-one :model/Collection :id id) :parent_id)))diff --git a/test/metabase/app_db/setup_test.clj b/test/metabase/app_db/setup_test.cljindex 2501a8c5122..3e69310e83d 100644--- a/test/metabase/app_db/setup_test.clj+++ b/test/metabase/app_db/setup_test.clj@@ -129,7 +129,7 @@(deftest setup-a-mb-instance-running-version-lower-than-45(mt/test-drivers #{:h2 :mysql :postgres}(mt/with-temp-empty-app-db [conn driver/*driver*]- (with-redefs [liquibase/decide-liquibase-file (fn [& _args] @#'liquibase/changelog-legacy-file)]+ (mt/with-dynamic-fn-redefs [liquibase/decide-liquibase-file (fn [& _args] @#'liquibase/changelog-legacy-file)];; set up a db in a way we have a MB instance running metabase 44(update-to-changelog-id "v44.00-000" conn))(is (= :done@@ -138,7 +138,7 @@(deftest setup-a-mb-instance-running-version-greater-than-45(mt/test-drivers #{:h2 :mysql :postgres}(mt/with-temp-empty-app-db [conn driver/*driver*]- (with-redefs [liquibase/decide-liquibase-file (fn [& _args] @#'liquibase/changelog-legacy-file)]+ (mt/with-dynamic-fn-redefs [liquibase/decide-liquibase-file (fn [& _args] @#'liquibase/changelog-legacy-file)];; set up a db in a way we have a MB instance running metabase 45(update-to-changelog-id "v45.00-001" conn))(is (= :done@@ -152,14 +152,14 @@;; the latest changeSet in `000_legacy_migrations.yaml` is `v44.00-044`. We can simulate a downgrade to that;; version by telling Liquibase that's the migrations file.- (with-redefs [liquibase/decide-liquibase-file (fn [& _args] "liquibase_legacy_migrations.yaml")]+ (mt/with-dynamic-fn-redefs [liquibase/decide-liquibase-file (fn [& _args] "liquibase_legacy_migrations.yaml")](is (thrown-with-msg?Exception #"You must run `java --add-opens java.base/java.nio=ALL-UNNAMED -jar metabase.jar migrate down` from version 45."(#'mdb.setup/error-if-downgrade-required! (mdb.connection/data-source)))));; check that the error correctly reports the version to run `downgrade` from(update-to-changelog-id "v46.00-001" conn)- (with-redefs [liquibase/decide-liquibase-file (fn [& _args] "liquibase_legacy_migrations.yaml")]+ (mt/with-dynamic-fn-redefs [liquibase/decide-liquibase-file (fn [& _args] "liquibase_legacy_migrations.yaml")](is (thrown-with-msg?Exception #"You must run `java --add-opens java.base/java.nio=ALL-UNNAMED -jar metabase.jar migrate down` from version 46."(#'mdb.setup/error-if-downgrade-required! (mdb.connection/data-source))))))))diff --git a/test/metabase/audit_app/task/truncate_audit_tables_test.clj b/test/metabase/audit_app/task/truncate_audit_tables_test.cljindex 98afef4c5ed..aa5dc9159dc 100644--- a/test/metabase/audit_app/task/truncate_audit_tables_test.clj+++ b/test/metabase/audit_app/task/truncate_audit_tables_test.clj@@ -34,7 +34,7 @@:model/QueryExecution {qe3-id :id} (merge (query-execution-defaults){:started_at (t/minus (t/offset-date-time) (t/years 1))})];; Mock a cloud environment so that we can change the setting value via env var- (with-redefs [premium-features/is-hosted? (constantly true)]+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly true)](testing "When the threshold is 0 (representing infinity), no rows are deleted"(mt/with-temp-env-var-value! [mb-audit-max-retention-days 0](#'task.truncate-audit-tables/truncate-audit-tables!)diff --git a/test/metabase/channel/api/channel_test.clj b/test/metabase/channel/api/channel_test.cljindex 4230fe9e190..784238a621f 100644--- a/test/metabase/channel/api/channel_test.clj+++ b/test/metabase/channel/api/channel_test.clj@@ -237,7 +237,7 @@(testing "audit log for channel apis"(mt/with-premium-features #{:audit-app}(mt/with-model-cleanup [:model/Channel]- (with-redefs [premium-features/enable-cache-granular-controls? (constantly true)]+ (mt/with-dynamic-fn-redefs [premium-features/enable-cache-granular-controls? (constantly true)](let [id (:id (mt/user-http-request :crowberto :post 200 "channel" default-test-channel))](testing "POST /api/channel"(is (= {:details {:description "Test channel description"diff --git a/test/metabase/channel/api/email_test.clj b/test/metabase/channel/api/email_test.cljindex 8e398c8bdac..ccd78387935 100644--- a/test/metabase/channel/api/email_test.clj+++ b/test/metabase/channel/api/email_test.clj@@ -115,7 +115,7 @@email-smtp-port "123"email-smtp-username "pre-user"email-smtp-password "pre-pass"]- (with-redefs [email/test-smtp-connection (fn [settings] settings)]+ (mt/with-dynamic-fn-redefs [email/test-smtp-connection (fn [settings] settings)](is (= "pre-user" (setting/get-value-of-type :string :email-smtp-username)))(is (= "pre-pass" (setting/get-value-of-type :string :email-smtp-password)))(is (= 123 (setting/get-value-of-type :integer :email-smtp-port)))@@ -140,7 +140,7 @@MB_EMAIL_SMTP_USERNAME nilMB_EMAIL_SMTP_PASSWORD nil](tu/discard-setting-changes [email-smtp-host email-smtp-port email-smtp-security email-smtp-username email-smtp-password]- (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-settings(assoc :with-corrections {})(update :email-smtp-security name))diff --git a/test/metabase/channel/api/slack_test.clj b/test/metabase/channel/api/slack_test.cljindex b8d85d65ca0..2596124bd37 100644--- a/test/metabase/channel/api/slack_test.clj+++ b/test/metabase/channel/api/slack_test.clj@@ -13,10 +13,10 @@(deftest update-slack-settings-test(testing "PUT /api/slack/settings"(testing "An admin can set a valid Slack app token to the slack-app-token setting"- (with-redefs [slack/valid-token? (constantly true)- slack/channel-exists? (constantly true)- slack/refresh-channels-and-usernames! (constantly nil)- slack/refresh-channels-and-usernames-when-needed! (constantly nil)]+ (mt/with-dynamic-fn-redefs [slack/valid-token? (constantly true)+ slack/channel-exists? (constantly true)+ slack/refresh-channels-and-usernames! (constantly nil)+ slack/refresh-channels-and-usernames-when-needed! (constantly nil)](mt/with-temporary-setting-values [slack-app-token nil](mt/user-http-request :crowberto :put 200 "slack/settings" {:slack-app-token "fake-token"})(is (= "fake-token" (channel.settings/unobfuscated-slack-app-token))))))))@@ -72,12 +72,12 @@(deftest app-info-test(testing "GET /api/slack/app-info"(testing "Returns app_id and team_id when Slack is configured"- (with-redefs [api.slack/app-info (constantly {:app_id "A12345"- :team_id "T67890"- :scopes {:actual ["chat:write"]- :required ["chat:write"]- :missing []- :extra []}})]+ (mt/with-dynamic-fn-redefs [api.slack/app-info (constantly {:app_id "A12345"+ :team_id "T67890"+ :scopes {:actual ["chat:write"]+ :required ["chat:write"]+ :missing []+ :extra []}})](mt/with-temporary-setting-values [slack-app-token "fake-token"](let [response (mt/user-http-request :crowberto :get 200 "slack/app-info")](is (= {:app_id "A12345"@@ -139,9 +139,9 @@:url "https://files.slack.com/files-pri/123/diagnostic.json"}]}]](testing "should post bug report to Slack with correct blocks"- (with-redefs [slack/upload-file! (constantly mock-file-info)- slack/post-chat-message! (constantly nil)- slack/channel-exists? (constantly true)]+ (mt/with-dynamic-fn-redefs [slack/upload-file! (constantly mock-file-info)+ slack/post-chat-message! (constantly nil)+ slack/channel-exists? (constantly true)](mt/with-temporary-setting-values [slack-bug-report-channel "test-bugs"](let [response (mt/user-http-request :crowberto :post 200 "slack/bug-report"{:diagnosticInfo diagnostic-info})]@@ -151,9 +151,9 @@response))))))(testing "should handle anonymous reports"- (with-redefs [slack/upload-file! (constantly mock-file-info)- slack/post-chat-message! (constantly nil)- slack/channel-exists? (constantly true)]+ (mt/with-dynamic-fn-redefs [slack/upload-file! (constantly mock-file-info)+ slack/post-chat-message! (constantly nil)+ slack/channel-exists? (constantly true)](mt/with-temporary-setting-values [slack-bug-report-channel "test-bugs"](let [anonymous-info (dissoc diagnostic-info :reporter)anonymous-blocks (walk/postwalkdiff --git a/test/metabase/channel/email/result_attachment_test.clj b/test/metabase/channel/email/result_attachment_test.cljindex ecea4aaba90..531019e5bd8 100644--- a/test/metabase/channel/email/result_attachment_test.clj+++ b/test/metabase/channel/email/result_attachment_test.clj@@ -2,7 +2,8 @@(:require[clojure.test :refer :all][metabase.channel.email.result-attachment :as email.result-attachment]- [metabase.permissions.core :as perms])+ [metabase.permissions.core :as perms]+ [metabase.test :as mt])(:import(java.io IOException)))@@ -38,15 +39,15 @@part {:card card:result {:row_count 5:data {:rows [[1] [2] [3] [4] [5]]}}}]- (with-redefs [perms/download-perms-level (fn [_query user-id]- (case (long user-id)- 1 :no- 2 :one-million-rows- :one-million-rows))+ (mt/with-dynamic-fn-redefs [perms/download-perms-level (fn [_query user-id]+ (case (long user-id)+ 1 :no+ 2 :one-million-rows+ :one-million-rows));; Sentinel: if execution reaches the streaming path, the perm check passed.;; We avoid exercising real CSV streaming machinery in a unit test.- email.result-attachment/create-temp-file! (fn [_]- (throw (ex-info "PERM-CHECK-PASSED" {})))]+ email.result-attachment/create-temp-file! (fn [_]+ (throw (ex-info "PERM-CHECK-PASSED" {})))](testing "passes perm check when subscription creator has download perms (even if card author does not)"(is (thrown-with-msg?clojure.lang.ExceptionInfodiff --git a/test/metabase/channel/email_test.clj b/test/metabase/channel/email_test.cljindex 5a4c0f7be77..0423518e18e 100644--- a/test/metabase/channel/email_test.clj+++ b/test/metabase/channel/email_test.clj@@ -14,6 +14,7 @@[metabase.premium-features.test-util :as premium-features.test-util][metabase.test.data.users :as test.users][metabase.test.util :as tu]+ [metabase.test.util.dynamic-redefs :as dynamic-redefs][metabase.util :as u :refer [prog1]][metabase.util.retry :as retry][postal.core :as postal]@@ -298,7 +299,7 @@(testing "error metrics collection"(tu/with-prometheus-system! [_ system](binding [retry/*test-time-config-hook* #(assoc % :max-retries 0)]- (with-redefs [email/send-email! (fn [_ _] (throw (Exception. "test-exception")))]+ (dynamic-redefs/with-dynamic-fn-redefs [email/send-email! (fn [_ _] (throw (Exception. "test-exception")))](email/send-message!:subject "101 Reasons to use Metabase":recipients ["[email protected]"]@@ -373,7 +374,7 @@(deftest send-message!-cloud-test(premium-features.test-util/with-premium-features [:cloud-custom-smtp]- (with-redefs [premium-features/is-hosted? (constantly true)]+ (dynamic-redefs/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly true)](tu/with-temporary-setting-values [email-from-address "[email protected]"email-from-name "From Name"email-reply-to ["[email protected]" "[email protected]"]@@ -414,7 +415,7 @@(deftest throttle-test(let [send-email (fn [recipients]- (with-redefs [postal/send-message (fn [& args] (last args))]+ (dynamic-redefs/with-dynamic-fn-redefs [postal/send-message (fn [& args] (last args))](email/send-email!{}(merge {:from "[email protected]"diff --git a/test/metabase/channel/impl/email_test.clj b/test/metabase/channel/impl/email_test.cljindex 8627900eda7..c2f500089e6 100644--- a/test/metabase/channel/impl/email_test.clj+++ b/test/metabase/channel/impl/email_test.clj@@ -12,8 +12,8 @@(deftest bcc-enabled-test(testing "When bcc is not enabled, return an email that uses to:"(let [sent-message (atom nil)]- (with-redefs [email/send-email! (fn [_ message]- (reset! sent-message message))]+ (mt/with-dynamic-fn-redefs [email/send-email! (fn [_ message]+ (reset! sent-message message))](mt/with-temporary-setting-values [email-from-address "[email protected]"email-smtp-host "fake_smtp_host"email-smtp-port 587@@ -36,7 +36,7 @@:dashboard_card_id 100:include_csv true:include_xls true}- result (with-redefs [render.util/is-visualizer-dashcard? (constantly true)]+ result (mt/with-dynamic-fn-redefs [render.util/is-visualizer-dashcard? (constantly true)](#'email.impl/assoc-attachment-booleans [matching-part-config] [visualizer-part]))](is (true? (-> result first :card :include_csv))diff --git a/test/metabase/channel/impl/slack_test.clj b/test/metabase/channel/impl/slack_test.cljindex 1c6b45d5795..be87c057618 100644--- a/test/metabase/channel/impl/slack_test.clj+++ b/test/metabase/channel/impl/slack_test.clj@@ -32,7 +32,7 @@(deftest slack-post-receives-at-most-50-blocks-test(let [block-inputs (atom [])]- (with-redefs [slack/post-chat-message! (fn [message-content] (swap! block-inputs conj (:blocks message-content)))]+ (mt/with-dynamic-fn-redefs [slack/post-chat-message! (fn [message-content] (swap! block-inputs conj (:blocks message-content)))](channel/send!{:type :channel/slack}{:channel "#not-a-channel"@@ -48,8 +48,8 @@{:type :card:card {:id 1:name "> click <https://c.com|here>"}}]- processed (with-redefs [slack/upload-file! (fn [_ _]- {:id "uploaded"})]+ processed (mt/with-dynamic-fn-redefs [slack/upload-file! (fn [_ _]+ {:id "uploaded"})](mt/with-temporary-setting-values [site-url "a.com"](mapv #'channel.slack/part->sections! parts)))](is (= [[{:type "section", :text {:type "mrkdwn", :text "<http://a.com/question/1|&amp;a>", :verbatim true}}@@ -125,7 +125,7 @@:creator {:common_name "Test User"}}recipient {:type :notification-recipient/raw-value:details {:value "#foo"}}- processed (with-redefs [slack/upload-file! (constantly {:url "a.com", :id "id"})]+ processed (mt/with-dynamic-fn-redefs [slack/upload-file! (constantly {:url "a.com", :id "id"})](channel/render-notification :channel/slack notification {:recipients [recipient]}))](->> processed first :blocks last :fields (map :text))))))](when config/ee-available?@@ -154,7 +154,7 @@:creator {:common_name "Test User"}}recipient {:type :notification-recipient/raw-value:details {:value "#test-channel"}}]- (with-redefs [slack/upload-file! (fn [_ _] {:id "uploaded-file-id"})]+ (mt/with-dynamic-fn-redefs [slack/upload-file! (fn [_ _] {:id "uploaded-file-id"})](mt/with-temporary-setting-values [site-url "http://example.com"](let [processed (channel/render-notification :channel/slack notification {:recipients [recipient]})card-section (-> processed first :blocks (nth 3))]diff --git a/test/metabase/channel/render/style_test.clj b/test/metabase/channel/render/style_test.cljindex 7ab0fd82a31..eee2039dced 100644--- a/test/metabase/channel/render/style_test.clj+++ b/test/metabase/channel/render/style_test.clj@@ -35,8 +35,8 @@(is (= nil(#'style/register-fonts-if-needed!))))(testing "If font registration fails, we should an Exception with a useful error message"- (with-redefs [style/register-font! (fn [& _]- (throw (ex-info "Oops!" {})))]+ (mt/with-dynamic-fn-redefs [style/register-font! (fn [& _]+ (throw (ex-info "Oops!" {})))](mt/with-log-messages-for-level [messages :error](is (thrown-with-msg?clojure.lang.ExceptionInfodiff --git a/test/metabase/channel/settings_test.clj b/test/metabase/channel/settings_test.cljindex 76baa0da408..b782ab23e14 100644--- a/test/metabase/channel/settings_test.clj+++ b/test/metabase/channel/settings_test.clj@@ -86,7 +86,7 @@(let [channels [{:display-name "#general" :name "general" :id "C001"}{:display-name "#data-team" :name "data-team" :id "C002"}{:display-name "@alice" :name "alice" :id "U001"}]]- (with-redefs [channel.settings/slack-cached-channels-and-usernames (constantly {:channels channels})]+ (mt/with-dynamic-fn-redefs [channel.settings/slack-cached-channels-and-usernames (constantly {:channels channels})](testing "finds by name"(is (= {:display-name "#general" :name "general" :id "C001"}(channel.settings/find-cached-slack-channel-or-username "general"))))diff --git a/test/metabase/cloud_migration/api_test.clj b/test/metabase/cloud_migration/api_test.cljindex e7ce80665c9..533eced1333 100644--- a/test/metabase/cloud_migration/api_test.clj+++ b/test/metabase/cloud_migration/api_test.clj@@ -25,7 +25,7 @@(mt/user-http-request :crowberto :put 200 "cloud-migration/cancel")))(deftest hosted-test- (with-redefs [premium-features/is-hosted? (constantly true)]+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly true)](mt/user-http-request :crowberto :post 400 "cloud-migration")))(deftest lifecycle-testdiff --git a/test/metabase/cloud_migration/models/cloud_migration_test.clj b/test/metabase/cloud_migration/models/cloud_migration_test.cljindex d23a2bbbb18..f1ad6213f07 100644--- a/test/metabase/cloud_migration/models/cloud_migration_test.clj+++ b/test/metabase/cloud_migration/models/cloud_migration_test.clj@@ -46,11 +46,15 @@:dump []:upload []:done []})- orig-set-progress @#'cloud-migration/set-progress]- (with-redefs [cloud-migration/cluster? (constantly false)- cloud-migration/set-progress (fn [id state n]- (swap! progress-calls update state conj n)- (orig-set-progress id state n))]+ orig-set-progress (mt/original-fn #'cloud-migration/set-progress)]+ ;; The redefs below are read on the test thread before the scheduler stops/starts;+ ;; if a future change dispatches `cluster?` or `set-progress` through a quartz worker+ ;; (which doesn't inherit `*local-redefs*`), revert that site to `with-redefs` per+ ;; the docstring of `with-dynamic-fn-redefs`.+ (mt/with-dynamic-fn-redefs [cloud-migration/cluster? (constantly false)+ cloud-migration/set-progress (fn [id state n]+ (swap! progress-calls update state conj n)+ (orig-set-progress id state n))](http-fake/with-fake-routes-in-isolation (fake-upload-route-handler migration)(testing "works"(try@@ -67,7 +71,7 @@(deftest migrate!-test-managed-scheduler(let [migration (mock-external-calls! (mt/user-http-request :crowberto :post 200 "cloud-migration"))]- (with-redefs [cloud-migration/cluster? (constantly false)]+ (mt/with-dynamic-fn-redefs [cloud-migration/cluster? (constantly false)](http-fake/with-fake-routes-in-isolation (fake-upload-route-handler migration)(testing "works when quartz scheduler is running"(task/start-scheduler!)@@ -111,10 +115,10 @@(testing "uses staging url"(is (= "https://store.staging.metabase.com" (#'cloud-migration.settings/store-url-default))))(testing "But can force to prod"- (with-redefs [config/config-bool (fn [k] (when (= k :mb-store-use-staging) false))]+ (mt/with-dynamic-fn-redefs [config/config-bool (fn [k] (when (= k :mb-store-use-staging) false))](is (= "https://store.metabase.com" (#'cloud-migration.settings/store-url-default)))))))(testing "with custom url is set"- (with-redefs [config/config-str (fn [k] (when (= k :mb-store-url) "https://custom.store.com"))]+ (mt/with-dynamic-fn-redefs [config/config-str (fn [k] (when (= k :mb-store-url) "https://custom.store.com"))](testing "in dev is honored"(with-redefs [config/is-dev? true](is (= "https://custom.store.com" (#'cloud-migration.settings/store-url-default)))))diff --git a/test/metabase/cmd/command_dox_test.clj b/test/metabase/cmd/command_dox_test.cljindex f233cabcfff..ee058e65558 100644--- a/test/metabase/cmd/command_dox_test.clj+++ b/test/metabase/cmd/command_dox_test.clj@@ -2,7 +2,8 @@(:require[clojure.string :as str][clojure.test :refer :all]- [metabase.cmd.command-dox :as sut]))+ [metabase.cmd.command-dox :as sut]+ [metabase.test :as mt]))(deftest ^:parallel format-arglist-test(testing "format-arglist handles various arglist patterns"@@ -153,8 +154,8 @@(deftest generate-documentation-test(testing "generate-documentation produces complete markdown document"- (let [doc (with-redefs [sut/header-section (constantly "# Test Header")- sut/footer-section (constantly "# Test Footer")]+ (let [doc (mt/with-dynamic-fn-redefs [sut/header-section (constantly "# Test Header")+ sut/footer-section (constantly "# Test Footer")](#'sut/generate-documentation))](testing "includes header"(is (str/starts-with? doc "# Test Header")))diff --git a/test/metabase/cmd/dump_to_h2_test.clj b/test/metabase/cmd/dump_to_h2_test.cljindex 712eb14530a..2b1c5e49845 100644--- a/test/metabase/cmd/dump_to_h2_test.clj+++ b/test/metabase/cmd/dump_to_h2_test.clj@@ -65,7 +65,7 @@h2-file-enc (format "out-%s.db" (mt/random-name))h2-file-default-enc (format "out-%s.db" (mt/random-name))](mt/test-drivers #{:h2 :postgres :mysql}- (with-redefs [i18n.impl/site-locale-from-setting (constantly nil)]+ (mt/with-dynamic-fn-redefs [i18n.impl/site-locale-from-setting (constantly nil)](binding [config/*disable-setting-cache* truemdb.connection/*application-db* (mdb.connection/application-dbdriver/*driver*@@ -113,7 +113,7 @@db-name (str "test_" (mt/random-name))](mt/with-temp-file [h2-file (format "out-%s.db" (mt/random-name))](mt/test-drivers #{:h2 :postgres :mysql}- (with-redefs [i18n.impl/site-locale-from-setting (constantly nil)]+ (mt/with-dynamic-fn-redefs [i18n.impl/site-locale-from-setting (constantly nil)](binding [config/*disable-setting-cache* truemdb.connection/*application-db* (mdb.connection/application-dbdriver/*driver*diff --git a/test/metabase/cmd/load_and_dump_test.clj b/test/metabase/cmd/load_and_dump_test.cljindex 2274ab389be..80322bc2785 100644--- a/test/metabase/cmd/load_and_dump_test.clj+++ b/test/metabase/cmd/load_and_dump_test.clj@@ -39,7 +39,7 @@(mdb/spec driver/*driver* details))))](binding [config/*disable-setting-cache* truemdb.connection/*application-db* (mdb.connection/application-db driver/*driver* data-source)]- (with-redefs [i18n.impl/site-locale-from-setting (constantly nil)]+ (mt/with-dynamic-fn-redefs [i18n.impl/site-locale-from-setting (constantly nil)](when-not (= driver/*driver* :h2)(tx/create-db! driver/*driver* {:database-name db-name}))(binding [copy/*copy-h2-database-details* true]diff --git a/test/metabase/collections/models/collection_test.clj b/test/metabase/collections/models/collection_test.cljindex 97055dfcb62..48e5117b495 100644--- a/test/metabase/collections/models/collection_test.clj+++ b/test/metabase/collections/models/collection_test.clj@@ -431,8 +431,8 @@(def ^:dynamic ^:private *visible-collection-ids* #{})(deftest effective-location-path-test- (with-redefs [audit/is-collection-id-audit? (constantly false)- collection/visible-collection-ids (fn [& _] *visible-collection-ids*)]+ (mt/with-dynamic-fn-redefs [audit/is-collection-id-audit? (constantly false)+ collection/visible-collection-ids (fn [& _] *visible-collection-ids*)](testing "valid input"(doseq [[[path visible-ids] expected] {["/10/20/30/" #{10 20}] "/10/20/"["/10/20/30/" #{10 30}] "/10/30/"@@ -833,7 +833,7 @@(testing "Let's make sure we get an Exception when we try to archive the Custom Reports Collection"(mt/with-temp [:model/Collection cr-collection {}]- (with-redefs [audit/default-custom-reports-collection (constantly cr-collection)]+ (mt/with-dynamic-fn-redefs [audit/default-custom-reports-collection (constantly cr-collection)](is (thrown-with-msg?Exception#"You cannot operate on the Custom Reports Collection."@@ -1780,8 +1780,8 @@:model/Collection cr-collection {}:model/Card cr-card {:collection_id (:id cr-collection)}:model/Dashboard cr-dashboard {:collection_id (:id cr-collection)}]- (with-redefs [audit/default-audit-collection (constantly audit-collection)- audit/default-custom-reports-collection (constantly cr-collection)]+ (mt/with-dynamic-fn-redefs [audit/default-audit-collection (constantly audit-collection)+ audit/default-custom-reports-collection (constantly cr-collection)](mt/with-current-user (mt/user->id :crowberto)(mt/with-additional-premium-features #{:audit-app}(is (not (mi/can-write? audit-collection))@@ -2099,7 +2099,7 @@;; When no dependencies, the function returns the model(let [model (t2/instance :model/Card {:id card-id})];; Mock to return empty set (new behavior)- (with-redefs [collection/non-remote-synced-dependencies (constantly #{})]+ (mt/with-dynamic-fn-redefs [collection/non-remote-synced-dependencies (constantly #{})](is (= model (collection/check-non-remote-synced-dependencies model))"Should return the model when no dependencies")))))@@ -2107,8 +2107,8 @@(mt/with-temp [:model/Card {card-id :id} {:name "Test Card"}:model/Card {dep-card-id :id} {:name "Dependency Card"}];; Mock to return a set of Card IDs (new behavior)- (with-redefs [collection/non-remote-synced-dependencies- (constantly #{dep-card-id})]+ (mt/with-dynamic-fn-redefs [collection/non-remote-synced-dependencies+ (constantly #{dep-card-id})](is (thrown-with-msg?clojure.lang.ExceptionInfo#"Uses content that is not remote synced."@@ -2119,7 +2119,7 @@(mt/with-temp [:model/Card {card-id :id} {:name "Test Card"}:model/Card {dep-card-id :id} {:name "Dependency Card"}];; Mock to return a set of Card IDs (new behavior)- (with-redefs [collection/non-remote-synced-dependencies (constantly #{dep-card-id})]+ (mt/with-dynamic-fn-redefs [collection/non-remote-synced-dependencies (constantly #{dep-card-id})](try(collection/check-non-remote-synced-dependencies (t2/instance :model/Card {:id card-id}))(catch Exception ediff --git a/test/metabase/collections_rest/api_test.clj b/test/metabase/collections_rest/api_test.cljindex 4b01682624f..b6841d1daf4 100644--- a/test/metabase/collections_rest/api_test.clj+++ b/test/metabase/collections_rest/api_test.clj@@ -288,7 +288,7 @@(is (= expected-lucky-tree(collection-tree-view ids response-lucky))))(testing "Mocking having one user still returns a correct result"- (with-redefs [t2/select-fn-set (constantly nil)]+ (mt/with-dynamic-fn-redefs [t2/select-fn-set (constantly nil)](let [response (mt/user-http-request :lucky :get 200 "collection/tree" :exclude-other-user-collections true)](is (= expected-lucky-tree(collection-tree-view ids response))))))))))diff --git a/test/metabase/core/perf_test.clj b/test/metabase/core/perf_test.cljindex 2111aabd555..ae4e1270596 100644--- a/test/metabase/core/perf_test.clj+++ b/test/metabase/core/perf_test.clj@@ -2,7 +2,8 @@(:require[clojure.test :refer [deftest is testing]][metabase.config.core :as config]- [metabase.core.perf :as perf])+ [metabase.core.perf :as perf]+ [metabase.test :as mt])(:import(java.nio.file Path)))@@ -20,11 +21,11 @@(deftest save-rate-minutes-test(testing "returns custom value when env var is set"- (with-redefs [config/config-int (constantly 10)]+ (mt/with-dynamic-fn-redefs [config/config-int (constantly 10)](is (= 10 (#'perf/save-rate-minutes 5)))(is (= 10 (#'perf/save-rate-minutes 30)))))(testing "falls back to default when env var is nil"- (with-redefs [config/config-int (constantly nil)]+ (mt/with-dynamic-fn-redefs [config/config-int (constantly nil)](is (= 5 (#'perf/save-rate-minutes 5)))(is (= 30 (#'perf/save-rate-minutes 30))))))diff --git a/test/metabase/dashboards_rest/api_test.clj b/test/metabase/dashboards_rest/api_test.cljindex efc514de13a..d48a35f1d66 100644--- a/test/metabase/dashboards_rest/api_test.clj+++ b/test/metabase/dashboards_rest/api_test.clj@@ -2957,7 +2957,7 @@(let [url (chain-filter-values-url dashboard (:category-name param-keys))](testing (str "\nGET /api/" url "\n")(testing "\nShow me names of categories that have expensive venues (price = 4), while I lack permissions."- (with-redefs [chain-filter/use-cached-field-values? (constantly false)]+ (mt/with-dynamic-fn-redefs [chain-filter/use-cached-field-values? (constantly false)](binding [qp.perms/*card-id* nil] ;; this situation was observed when running constrained chain filters.(is (= {:values [["African"] ["American"] ["Artisan"] ["Asian"]] :has_more_values false}(chain-filter-test/take-n-values 4 (mt/user-http-request :rasta :get 200 url)))))))))@@ -2965,7 +2965,7 @@(let [url (chain-filter-values-url dashboard (:category-name param-keys) (:price param-keys) 4)](testing (str "\nGET /api/" url "\n")(testing "\nShow me names of categories that have expensive venues (price = 4), while I lack permissions."- (with-redefs [chain-filter/use-cached-field-values? (constantly false)]+ (mt/with-dynamic-fn-redefs [chain-filter/use-cached-field-values? (constantly false)](binding [qp.perms/*card-id* nil](is (= {:values [["Japanese"] ["Steakhouse"]], :has_more_values false}(chain-filter-test/take-n-values 3 (mt/user-http-request :rasta :get 200 url)))))))))))@@ -3027,7 +3027,7 @@;; HACK: we currently 403 on chain-filter calls that require running a MBQL;; but 200 on calls that we could just use the cache.;; It's not ideal and we definitely need to have a consistent behavior- (with-redefs [chain-filter/use-cached-field-values? (fn [_] false)]+ (mt/with-dynamic-fn-redefs [chain-filter/use-cached-field-values? (fn [_] false)](is (= {:values [["African"] ["American"] ["Artisan"]]:has_more_values false}(->> (chain-filter-values-url (:id dashboard) (:category-name param-keys))@@ -3491,7 +3491,7 @@(testing "fallback to chain-filter"(let [mock-chain-filter-result {:has_more_values true:values [["chain-filter"]]}]- (with-redefs [parameters.dashboard/chain-filter (constantly mock-chain-filter-result)]+ (mt/with-dynamic-fn-redefs [parameters.dashboard/chain-filter (constantly mock-chain-filter-result)](testing "if value-field not found in source card"(mt/with-temp [:model/Card {card-id :id} {}:model/Dashboard dashboard {:parameters [{:id "abc"@@ -4975,7 +4975,7 @@(mt/user-http-request :crowberto :get 200 (format "dashboard/%d/params/%s/values" (:id dash) "_CATEGORY_NAME_"))))))(deftest ^:synchronized dashboard-query-metadata-cached-test- (let [original-admp @#'lib.metadata.jvm/application-database-metadata-provider-factory+ (let [original-admp (mt/original-fn #'lib.metadata.jvm/application-database-metadata-provider-factory)uncached-calls (atom -1)expected [{:name "Some dashboard"}{:tables [{} {}]@@ -4999,10 +4999,10 @@(reset! uncached-calls (call-count-fn))))(testing "cached requests"(let [provider-counts (atom {})]- (with-redefs [lib.metadata.jvm/application-database-metadata-provider-factory- (fn [database-id]- (swap! provider-counts update database-id (fnil inc 0))- (original-admp database-id))]+ (mt/with-dynamic-fn-redefs [lib.metadata.jvm/application-database-metadata-provider-factory+ (fn [database-id]+ (swap! provider-counts update database-id (fnil inc 0))+ (original-admp database-id))](t2/with-call-count [call-count-fn](let [load-id (str (random-uuid))](is (=? expecteddiff --git a/test/metabase/data_studio/api/table_test.clj b/test/metabase/data_studio/api/table_test.cljindex ff4b3096a70..f49ecf2756c 100644--- a/test/metabase/data_studio/api/table_test.clj+++ b/test/metabase/data_studio/api/table_test.clj@@ -96,10 +96,10 @@:model/Table {_ :id} {:db_id d2, :schema "PUBLIC"}:model/Table {t4 :id} {:db_id d2, :schema "PUBLIC"}:model/Table {t5 :id} {:db_id d2, :schema "FOO"}]- (with-redefs [sync/sync-table! (fn [table]- (swap! tables conj table)- (.countDown latch)- nil)]+ (mt/with-dynamic-fn-redefs [sync/sync-table! (fn [table]+ (swap! tables conj table)+ (.countDown latch)+ nil)](mt/user-http-request :crowberto :post 204 "data-studio/table/sync-schema" {:database_ids [d1],:schema_ids [(format "%d:FOO" d2)]:table_ids [t4]})@@ -124,10 +124,10 @@:model/Table {_ :id} {:db_id d2, :schema "PUBLIC"}:model/Table {t4 :id} {:db_id d2, :schema "PUBLIC"}:model/Table {t5 :id} {:db_id d2, :schema "FOO"}]- (with-redefs [sync/update-field-values-for-table! (fn [table]- (swap! tables conj table)- (.countDown latch)- nil)]+ (mt/with-dynamic-fn-redefs [sync/update-field-values-for-table! (fn [table]+ (swap! tables conj table)+ (.countDown latch)+ nil)](mt/user-http-request :crowberto :post 204 "data-studio/table/rescan-values" {:database_ids [d1],:schema_ids [(format "%d:FOO" d2)]:table_ids [t4]})diff --git a/test/metabase/documents/api/document_test.clj b/test/metabase/documents/api/document_test.cljindex 070f54a420c..40d142a41fd 100644--- a/test/metabase/documents/api/document_test.clj+++ b/test/metabase/documents/api/document_test.clj@@ -1719,8 +1719,8 @@(testing "archiving document publishes archive event"(mt/with-model-cleanup [:model/Document](let [events (atom [])]- (with-redefs [events/publish-event! (fn [topic event]- (swap! events conj {:topic topic :event event}))]+ (mt/with-dynamic-fn-redefs [events/publish-event! (fn [topic event]+ (swap! events conj {:topic topic :event event}))](mt/user-http-request :crowberto:put 200 (format "document/%s" doc-id){:archived true})@@ -1731,8 +1731,8 @@(testing "unarchiving document publishes update event"(mt/with-model-cleanup [:model/Document](let [events (atom [])]- (with-redefs [events/publish-event! (fn [topic event]- (swap! events conj {:topic topic :event event}))]+ (mt/with-dynamic-fn-redefs [events/publish-event! (fn [topic event]+ (swap! events conj {:topic topic :event event}))](mt/user-http-request :crowberto:put 200 (format "document/%s" doc-id){:archived false})@@ -1751,17 +1751,18 @@;; Simulate a failure during card archiving(testing "failure during card archiving rolls back document archiving"- (with-redefs [t2/update! (fn [model id updates]- (if (and (= model :model/Card) (:archived updates))- (throw (ex-info "Simulated card archive failure" {}))- (t2/update! model id updates)))]- (mt/user-http-request :crowberto- :put 500 (format "document/%s" doc-id)- {:archived true})+ (let [orig-update! (mt/original-fn #'t2/update!)]+ (mt/with-dynamic-fn-redefs [t2/update! (fn [model id updates]+ (if (and (= model :model/Card) (:archived updates))+ (throw (ex-info "Simulated card archive failure" {}))+ (orig-update! model id updates)))]+ (mt/user-http-request :crowberto+ :put 500 (format "document/%s" doc-id)+ {:archived true});; Verify document wasn't archived due to rollback- (is (false? (:archived (t2/select-one :model/Document :id doc-id))))- (is (false? (:archived (t2/select-one :model/Card :id card-id)))))))))+ (is (false? (:archived (t2/select-one :model/Document :id doc-id))))+ (is (false? (:archived (t2/select-one :model/Card :id card-id))))))))))(deftest document-archive-mixed-scenarios-test(testing "Mixed archiving scenarios - documents with different archival states"@@ -1955,8 +1956,8 @@:document (documents.test-util/text->prose-mirror-ast "Event test"):archived true}](let [events (atom [])]- (with-redefs [events/publish-event! (fn [topic event]- (swap! events conj {:topic topic :event event}))]+ (mt/with-dynamic-fn-redefs [events/publish-event! (fn [topic event]+ (swap! events conj {:topic topic :event event}))](mt/user-http-request :crowberto :delete 204 (format "document/%s" doc-id));; Should have published document-delete eventdiff --git a/test/metabase/documents/revisions/integration_test.clj b/test/metabase/documents/revisions/integration_test.cljindex 1f04ef07983..3b6b0d87ba2 100644--- a/test/metabase/documents/revisions/integration_test.clj+++ b/test/metabase/documents/revisions/integration_test.clj@@ -204,11 +204,11 @@(deftest document-revision-event-handler-integration-test(testing "Document revision events are published and handled correctly"- (let [original-event events/publish-event!+ (let [original-event (mt/original-fn #'events/publish-event!)events-received (atom [])]- (with-redefs [events/publish-event! (fn [topic event]- (swap! events-received conj [topic event])- (original-event topic event))]+ (mt/with-dynamic-fn-redefs [events/publish-event! (fn [topic event]+ (swap! events-received conj [topic event])+ (original-event topic event))](mt/with-temp [:model/Document {doc-id :id, :as document} {:name "Event Test Document":document {:type "doc" :content []}:creator_id (mt/user->id :rasta)}]diff --git a/test/metabase/documents/view_log_test.clj b/test/metabase/documents/view_log_test.cljindex 501b879f342..8a782c3aa70 100644--- a/test/metabase/documents/view_log_test.clj+++ b/test/metabase/documents/view_log_test.clj@@ -110,9 +110,9 @@:document "{\"type\":\"doc\",\"content\":[]}":creator_id (:id user)}](let [events-published (atom [])]- (with-redefs [events/publish-event! (fn [topic event]- (swap! events-published conj topic)- event)]+ (mt/with-dynamic-fn-redefs [events/publish-event! (fn [topic event]+ (swap! events-published conj topic)+ event)](#'documents.view-log/update-document-last-viewed-at!*[{:id (:id document) :timestamp (t/offset-date-time)}])(is (not (contains? (set @events-published) :event/document-update))diff --git a/test/metabase/driver/common/table_rows_sample_test.clj b/test/metabase/driver/common/table_rows_sample_test.cljindex bfb3df87272..800064dde0f 100644--- a/test/metabase/driver/common/table_rows_sample_test.clj+++ b/test/metabase/driver/common/table_rows_sample_test.clj@@ -141,12 +141,12 @@:fingerprint_version 0}))(let [fingerprints (atom [])fingerprint-query (atom nil)- orig-table-rows-sample-query @#'table-rows-sample/table-rows-sample-query]- (with-redefs [fingerprint/save-fingerprint! (fn [_field fingerprint]- (swap! fingerprints conj fingerprint))- table-rows-sample/table-rows-sample-query (fn [& args]- (reset! fingerprint-query- (apply orig-table-rows-sample-query args)))]+ orig-table-rows-sample-query (mt/original-fn #'table-rows-sample/table-rows-sample-query)]+ (mt/with-dynamic-fn-redefs [fingerprint/save-fingerprint! (fn [_field fingerprint]+ (swap! fingerprints conj fingerprint))+ table-rows-sample/table-rows-sample-query (fn [& args]+ (reset! fingerprint-query+ (apply orig-table-rows-sample-query args)))](fingerprint/fingerprint-table! (t2/select-one :model/Table :id (mt/id :string_nums)))(testing "empty expressions = no substring optimization in sample query = use of effective type"(is (empty? (lib/expressions @fingerprint-query))))@@ -173,8 +173,8 @@(lib/filters (#'table-rows-sample/table-rows-sample-query mp table [field1] {}))))))(testing "the mbql on a table that requires a filter will include a filter";; currently only applied for bigquery tables in which a table can have a required partition filter- (with-redefs [qp/process-query (fn [& args]- (first args))]+ (mt/with-dynamic-fn-redefs [qp/process-query (fn [& args]+ (first args))](is (=? [[:> {}[:field {:base-type :type/Integer} (:id field2)]int?]]diff --git a/test/metabase/driver/common_test.clj b/test/metabase/driver/common_test.cljindex 202bc00cf09..4f671c727db 100644--- a/test/metabase/driver/common_test.clj+++ b/test/metabase/driver/common_test.clj@@ -62,7 +62,7 @@(deftest cloud-ip-address-info-test(testing "The cloud-ip-address-info field is correctly resolved when fetching driver connection properties"(mt/with-temp-env-var-value! [mb-cloud-gateway-ips "1.2.3.4,5.6.7.8"]- (with-redefs [premium-features/is-hosted? (constantly true)]+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly true)];; make sure Postgres driver is initialized before trying to get its connection properties.(driver/the-initialized-driver :postgres)(let [connection-props (-> (driver.u/available-drivers-info)diff --git a/test/metabase/driver/h2_test.clj b/test/metabase/driver/h2_test.cljindex 86da0fa4d04..06b2c50b0df 100644--- a/test/metabase/driver/h2_test.clj+++ b/test/metabase/driver/h2_test.clj@@ -416,8 +416,8 @@(is (= {:type :metabase.actions.error/violate-unique-constraint,:message "Ranking already exists.",:errors {"RANKING" "This Ranking value already exists."}}- (with-redefs [h2.actions/constraint->column-names (fn [& _args]- ["RANKING"])]+ (mt/with-dynamic-fn-redefs [h2.actions/constraint->column-names (fn [& _args]+ ["RANKING"])](sql-jdbc.actions/maybe-parse-sql-error:h2 actions.error/violate-unique-constraint nil nil"Unique index or primary key violation: \"PUBLIC.CONSTRAINT_INDEX_4 ON PUBLIC.\"\"GROUP\"\"(RANKING NULLS FIRST) VALUES ( /* 1 */ 1 )\"; SQL statement:\nINSERT INTO \"PUBLIC\".\"GROUP\" (\"NAME\", \"RANKING\") VALUES (CAST(? AS VARCHAR), CAST(? AS INTEGER)) [23505-214]"))))))diff --git a/test/metabase/driver/impl_test.clj b/test/metabase/driver/impl_test.cljindex 401037977da..be6241babc7 100644--- a/test/metabase/driver/impl_test.clj+++ b/test/metabase/driver/impl_test.clj@@ -8,6 +8,7 @@[clojure.tools.namespace.find :as ns.find][metabase.driver :as driver][metabase.driver.impl :as driver.impl]+ [metabase.test :as mt][metabase.test.util.async :as tu.async])(:import(com.vladsch.flexmark.ast Heading)@@ -32,11 +33,11 @@;; until the namespace has completed loading.(tu.async/with-open-channels [started-loading-chan (a/promise-chan)](let [finished-loading (atom false)]- (with-redefs [driver.impl/require-driver-ns (fn [_]- (driver/register! ::race-condition-test)- (a/>!! started-loading-chan :start)- (Thread/sleep 100)- (reset! finished-loading true))]+ (mt/with-dynamic-fn-redefs [driver.impl/require-driver-ns (fn [_]+ (driver/register! ::race-condition-test)+ (a/>!! started-loading-chan :start)+ (Thread/sleep 100)+ (reset! finished-loading true))];; fire off a separate thread that will start loading the driver(future (driver/the-initialized-driver ::race-condition-test))(tu.async/wait-for-result started-loading-chan 500)diff --git a/test/metabase/driver/mysql_test.clj b/test/metabase/driver/mysql_test.cljindex c4b5b0e3053..bc930d617ce 100644--- a/test/metabase/driver/mysql_test.clj+++ b/test/metabase/driver/mysql_test.clj@@ -693,7 +693,7 @@(deftest actions-maybe-parse-sql-error-test-2(testing "violate unique constraint"- (with-redefs [mysql.actions/constraint->column-names (constantly ["PRIMARY"])]+ (mt/with-dynamic-fn-redefs [mysql.actions/constraint->column-names (constantly ["PRIMARY"])](is (=? {:type :metabase.actions.error/violate-unique-constraint,:message "Primary already exists.",:errors {"PRIMARY" "This Primary value already exists."}}@@ -877,7 +877,7 @@:additional-options "trustServerCertificate=true")](sql-jdbc.conn/with-connection-spec-for-testing-connection[spec [:mysql new-connection-details]]- (with-redefs [sql-jdbc.conn/db->pooled-connection-spec (fn [_] spec)]+ (mt/with-dynamic-fn-redefs [sql-jdbc.conn/db->pooled-connection-spec (fn [_] spec)](sql-jdbc.sync/current-user-table-privileges driver/*driver* spec {})))))](try(doseq [stmt ["CREATE TABLE `bar` (id INTEGER);"@@ -937,7 +937,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 sleep(3)"])]+ (mt/with-dynamic-fn-redefs [sql-jdbc.describe-database/simple-select-probe-query (constantly ["SELECT sleep(3)"])](binding [sql-jdbc.describe-database/*select-probe-query-timeout-seconds* 1](sql-jdbc.execute/do-with-connection-with-optionsdriver/*driver*diff --git a/test/metabase/driver/postgres_test.clj b/test/metabase/driver/postgres_test.cljindex 2ead6d0c578..5088db1cd36 100644--- a/test/metabase/driver/postgres_test.clj+++ b/test/metabase/driver/postgres_test.clj@@ -1210,7 +1210,7 @@(deftest actions-maybe-parse-sql-error-violate-unique-constraint-test(testing "violate unique constraint"- (with-redefs [postgres.actions/constraint->column-names (constantly ["ranking"])]+ (mt/with-dynamic-fn-redefs [postgres.actions/constraint->column-names (constantly ["ranking"])](is (=? {:type :metabase.actions.error/violate-unique-constraint,:message "Ranking already exists.",:errors {"ranking" "This Ranking value already exists."}}@@ -1622,9 +1622,9 @@(deftest can-set-ssl-key-via-gui(testing "ssl key can be set via the gui (#20319)"- (with-redefs [secret/value-as-file!- (fn [driver details secret-property & [_ext]]- (str "file:" secret-property "=" (u/bytes-to-string (:value (#'secret/resolve-secret-map driver details secret-property)))))]+ (mt/with-dynamic-fn-redefs [secret/value-as-file!+ (fn [driver details secret-property & [_ext]]+ (str "file:" secret-property "=" (u/bytes-to-string (:value (#'secret/resolve-secret-map driver details secret-property)))))](is (= "file:ssl-key=/clientkey.pkcs12"(:sslkey(#'postgres/ssl-params@@ -1697,7 +1697,7 @@get-privileges (fn [](sql-jdbc.conn/with-connection-spec-for-testing-connection[spec [:postgres (assoc (:details (mt/db)) :user "privilege_rows_test_example_role")]]- (with-redefs [sql-jdbc.conn/db->pooled-connection-spec (fn [_] spec)]+ (mt/with-dynamic-fn-redefs [sql-jdbc.conn/db->pooled-connection-spec (fn [_] spec)](set (sql-jdbc.sync/current-user-table-privileges driver/*driver* spec)))))](try(jdbc/execute! conn-spec (str@@ -1900,7 +1900,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 pg_sleep(3)"])]+ (mt/with-dynamic-fn-redefs [sql-jdbc.describe-database/simple-select-probe-query (constantly ["SELECT pg_sleep(3)"])](binding [sql-jdbc.describe-database/*select-probe-query-timeout-seconds* 1](sql-jdbc.execute/do-with-connection-with-optionsdriver/*driver*diff --git a/test/metabase/driver/sql_jdbc/connection_test.clj b/test/metabase/driver/sql_jdbc/connection_test.cljindex 0c5d63efae7..e88ff83dc8f 100644--- a/test/metabase/driver/sql_jdbc/connection_test.clj+++ b/test/metabase/driver/sql_jdbc/connection_test.clj@@ -68,13 +68,13 @@(testing "creating and removing specs works";; need to create a new, nonexistent h2 db(let [destroyed? (atom false)- original-destroy @#'sql-jdbc.conn/destroy-pool!+ original-destroy (mt/original-fn #'sql-jdbc.conn/destroy-pool!)pool-cache-key @#'sql-jdbc.conn/pool-cache-keyconnection-details {:db "mem:connection_test"}spec (mdb/spec :h2 connection-details)]- (with-redefs [sql-jdbc.conn/destroy-pool! (fn [id destroyed-spec]- (original-destroy id destroyed-spec)- (reset! destroyed? true))]+ (mt/with-dynamic-fn-redefs [sql-jdbc.conn/destroy-pool! (fn [id destroyed-spec]+ (original-destroy id destroyed-spec)+ (reset! destroyed? true))](sql-jdbc.execute/do-with-connection-with-options:h2spec@@ -731,7 +731,7 @@port (config/config-int :mb-postgres-aws-iam-test-port)user (config/config-str :mb-postgres-aws-iam-test-user)dbname (config/config-str :mb-postgres-aws-iam-test-dbname)]- (with-redefs [premium-features/is-hosted? (constantly false)]+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly false)](testing "Connection details are configured"(is (string? host))(is (string? user))@@ -757,7 +757,7 @@user (config/config-str :mb-mysql-aws-iam-test-user)dbname (config/config-str :mb-mysql-aws-iam-test-dbname)ssl-cert (config/config-str :mb-mysql-aws-iam-test-ssl-cert)]- (with-redefs [premium-features/is-hosted? (constantly false)]+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly false)](testing "Connection details are configured"(is (string? host))(is (string? user))@@ -961,8 +961,8 @@(.put cache cache-key (assoc pool-1 :tunnel-session :mock-closed-session)));; Mock ssh-tunnel-open? to return false for our mock session- (with-redefs [ssh/ssh-tunnel-open? (fn [pool-spec]- (not= :mock-closed-session (:tunnel-session pool-spec)))]+ (mt/with-dynamic-fn-redefs [ssh/ssh-tunnel-open? (fn [pool-spec]+ (not= :mock-closed-session (:tunnel-session pool-spec)))];; Next call should detect invalid pool and recreate(let [pool-2 (sql-jdbc.conn/db->pooled-connection-spec db)](is (= 2 @create-count) "Pool should have been recreated due to closed tunnel")diff --git a/test/metabase/driver/sql_jdbc/execute_test.clj b/test/metabase/driver/sql_jdbc/execute_test.cljindex 1e26ec3915a..5f4dd552e63 100644--- a/test/metabase/driver/sql_jdbc/execute_test.clj+++ b/test/metabase/driver/sql_jdbc/execute_test.clj@@ -30,19 +30,19 @@(mt/test-drivers (descendants driver/hierarchy :sql-jdbc)(let [test-db-id (mt/id) ;; Get the test database IDconnection-count (volatile! 0)- orig-do-with-resolved-connection-data-source @#'sql-jdbc.execute/do-with-resolved-connection-data-source]- (with-redefs [sql-jdbc.execute/do-with-resolved-connection-data-source- (fn [driver db opts]+ orig-do-with-resolved-connection-data-source (mt/original-fn #'sql-jdbc.execute/do-with-resolved-connection-data-source)]+ (mt/with-dynamic-fn-redefs [sql-jdbc.execute/do-with-resolved-connection-data-source+ (fn [driver db opts];; Only count connections for our test database because on startup the audit-db will be;; synced, which causes this to fail intermittently because it creates connections (to db;; 13371337)- (if (= db test-db-id)- (reify javax.sql.DataSource- (getConnection [_]- (vswap! connection-count inc)- (.getConnection ^DataSource (orig-do-with-resolved-connection-data-source driver db opts))))+ (if (= db test-db-id)+ (reify javax.sql.DataSource+ (getConnection [_]+ (vswap! connection-count inc)+ (.getConnection ^DataSource (orig-do-with-resolved-connection-data-source driver db opts))));; For other databases (like audit DB), just pass through- (orig-do-with-resolved-connection-data-source driver db opts)))]+ (orig-do-with-resolved-connection-data-source driver db opts)))](let [closed-conn (doto (.getConnection ^DataSource(orig-do-with-resolved-connection-data-source driver/*driver* test-db-id {}))(.close))]@@ -64,12 +64,12 @@(mt/test-drivers (descendants driver/hierarchy :sql-jdbc)(let [test-db-id (mt/id)captured-connection-type (volatile! nil)- orig-fn @#'sql-jdbc.execute/do-with-resolved-connection-data-source]- (with-redefs [sql-jdbc.execute/do-with-resolved-connection-data-source- (fn [driver db opts]- (when (and (= db test-db-id) (:keep-open? opts))- (vreset! captured-connection-type driver.conn/*connection-type*))- (orig-fn driver db opts))]+ orig-fn (mt/original-fn #'sql-jdbc.execute/do-with-resolved-connection-data-source)]+ (mt/with-dynamic-fn-redefs [sql-jdbc.execute/do-with-resolved-connection-data-source+ (fn [driver db opts]+ (when (and (= db test-db-id) (:keep-open? opts))+ (vreset! captured-connection-type driver.conn/*connection-type*))+ (orig-fn driver db opts))](let [closed-conn (doto (.getConnection ^DataSource(orig-fn driver/*driver* test-db-id {}))(.close))]diff --git a/test/metabase/driver/sql_jdbc/sync/describe_database_test.clj b/test/metabase/driver/sql_jdbc/sync/describe_database_test.cljindex 433f14cc8b7..30ce39fc657 100644--- a/test/metabase/driver/sql_jdbc/sync/describe_database_test.clj+++ b/test/metabase/driver/sql_jdbc/sync/describe_database_test.clj@@ -71,7 +71,7 @@nil(fn [^Connection conn];; We have to mock this to make it work with all DBs- (with-redefs [sql-jdbc.describe-database/all-schemas (constantly #{"PUBLIC"})]+ (mt/with-dynamic-fn-redefs [sql-jdbc.describe-database/all-schemas (constantly #{"PUBLIC"})](->> (into [] (sql-jdbc.describe-database/fast-active-tables (or driver/*driver* :h2) conn nil nil))(map :name)sort)))))))@@ -103,13 +103,13 @@objects the sync process left open. Make sure you wrap ResultSets with `with-open`! Otherwise some JDBC drivers likeOracle and Redshift will keep open cursors indefinitely."[driver db]- (let [orig-result-set-seq jdbc/result-set-seq+ (let [orig-result-set-seq (mt/original-fn #'jdbc/result-set-seq)resultsets (atom [])];; swap out `jdbc/result-set-seq` which is what ultimately gets called on result sets with a function that will;; stash the ResultSet object in an atom so we can check whether its closed later- (with-redefs [jdbc/result-set-seq (fn [^ResultSet rs & more]- (swap! resultsets conj rs)- (apply orig-result-set-seq rs more))]+ (mt/with-dynamic-fn-redefs [jdbc/result-set-seq (fn [^ResultSet rs & more]+ (swap! resultsets conj rs)+ (apply orig-result-set-seq rs more))];; taking advantage of the fact that `sql-jdbc.describe-database/describe-database` can accept JBDC connections;; instead of databases; by doing this we can keep the connection open and check whether resultsets are still;; open before they would normally get closed@@ -284,14 +284,14 @@:+fns [jdbc-describe-database]:-features [:table-privileges]})(let [closed-first (volatile! false)- execute-select-probe-query @#'sql-jdbc.describe-database/execute-select-probe-query+ execute-select-probe-query (mt/original-fn #'sql-jdbc.describe-database/execute-select-probe-query)all-tables (driver/describe-database driver/*driver* (mt/id))]- (with-redefs [sql-jdbc.describe-database/execute-select-probe-query- (fn [driver ^Connection conn query]- (when-not @closed-first- (vreset! closed-first true)- (.close conn))- (execute-select-probe-query driver conn query))]+ (mt/with-dynamic-fn-redefs [sql-jdbc.describe-database/execute-select-probe-query+ (fn [driver ^Connection conn query]+ (when-not @closed-first+ (vreset! closed-first true)+ (.close conn))+ (execute-select-probe-query driver conn query))](let [table-names #(->> % :tables (map :name) set)all-tables-sans-one (table-names (driver/describe-database driver/*driver* (mt/id)))];; there is at maximum one missing table@@ -304,6 +304,7 @@driver/*driver* (mt/db) nil(fn [^Connection conn](let [select-probes (atom 0)]+ ;; query-canceled? is a multimethod, so we can't use with-dynamic-fn-redefs for the pair.(with-redefs [sql-jdbc.describe-database/execute-select-probe-query(fn [_driver conn' [sql]](let [n (swap! select-probes inc)]diff --git a/test/metabase/driver/sql_jdbc/sync/describe_table_test.clj b/test/metabase/driver/sql_jdbc/sync/describe_table_test.cljindex c5841d7ed3b..30a2c6fc778 100644--- a/test/metabase/driver/sql_jdbc/sync/describe_table_test.clj+++ b/test/metabase/driver/sql_jdbc/sync/describe_table_test.clj@@ -216,9 +216,9 @@(deftest database-types-fallback-test(mt/test-drivers (apply disj (sql-jdbc-drivers-using-default-describe-table-or-fields-impl)(tqpt/timeseries-drivers))- (let [org-result-set-seq jdbc/result-set-seq]- (with-redefs [jdbc/result-set-seq (fn [& args]- (map #(dissoc % :type_name) (apply org-result-set-seq args)))]+ (let [org-result-set-seq (mt/original-fn #'jdbc/result-set-seq)]+ (mt/with-dynamic-fn-redefs [jdbc/result-set-seq (fn [& args]+ (map #(dissoc % :type_name) (apply org-result-set-seq args)))](is (= #{{:name "longitude" :base-type :type/Float}{:name "category_id" :base-type :type/Integer}{:name "price" :base-type :type/Integer}diff --git a/test/metabase/driver_test.clj b/test/metabase/driver_test.cljindex 7504da61a59..c561eb94f4a 100644--- a/test/metabase/driver_test.clj+++ b/test/metabase/driver_test.clj@@ -45,7 +45,7 @@(.getContextClassLoader (Thread/currentThread))))))(deftest available?-test- (with-redefs [driver.impl/concrete? (constantly true)]+ (mt/with-dynamic-fn-redefs [driver.impl/concrete? (constantly true)](is (driver/available? ::test-driver))(is (driver/available? "metabase.driver-test/test-driver")"`driver/available?` should work for if `driver` is a string -- see #10135")))diff --git a/test/metabase/embedding_rest/api/embed_test.clj b/test/metabase/embedding_rest/api/embed_test.cljindex fd5263f8ee6..13128787693 100644--- a/test/metabase/embedding_rest/api/embed_test.clj+++ b/test/metabase/embedding_rest/api/embed_test.clj@@ -390,7 +390,7 @@(testing (str "Downloading CSV/JSON/XLSX results shouldn't be subject to the default query constraints -- even if ""the query comes in with `add-default-userland-constraints` (as will be the case if the query gets ""saved from one that had it -- see #9831 and #10399)")- (with-redefs [qp.constraints/default-query-constraints (constantly {:max-results 10, :max-results-bare-rows 10})]+ (mt/with-dynamic-fn-redefs [qp.constraints/default-query-constraints (constantly {:max-results 10, :max-results-bare-rows 10})](with-embedding-enabled-and-new-secret-key!(with-temp-card [card {:enable_embedding true:dataset_query (assoc (mt/mbql-query venues)@@ -779,7 +779,7 @@(deftest downloading-csv-json-xlsx-results-from-the-dashcard-endpoint-shouldn-t-be-subject-to-the-default-query-constraints(testing (str "Downloading CSV/JSON/XLSX results from the dashcard endpoint shouldn't be subject to the default ""query constraints (#10399)")- (with-redefs [qp.constraints/default-query-constraints (constantly {:max-results 10, :max-results-bare-rows 10})]+ (mt/with-dynamic-fn-redefs [qp.constraints/default-query-constraints (constantly {:max-results 10, :max-results-bare-rows 10})](with-embedding-enabled-and-new-secret-key!(with-temp-dashcard [dashcard {:dash {:enable_embedding true}:card {:dataset_query (assoc (mt/mbql-query venues)@@ -829,7 +829,7 @@(deftest downloading-csv-json-xlsx-results-from-the-dashcard-endpoint-respects-column-settings(testing "Downloading CSV/JSON/XLSX results should respect the column settings of the dashcard, such as column order and hidden/shown setting. (#33727)"- (with-redefs [qp.constraints/default-query-constraints (constantly {:max-results 10, :max-results-bare-rows 10})]+ (mt/with-dynamic-fn-redefs [qp.constraints/default-query-constraints (constantly {:max-results 10, :max-results-bare-rows 10})](with-embedding-enabled-and-new-secret-key!(with-temp-dashcard [dashcard {:dash {:enable_embedding true}:card {:dataset_query (assoc (mt/mbql-query venues)diff --git a/test/metabase/geojson/api_test.clj b/test/metabase/geojson/api_test.cljindex 5994cd15a05..f2305cfa2e5 100644--- a/test/metabase/geojson/api_test.clj+++ b/test/metabase/geojson/api_test.clj@@ -160,7 +160,7 @@;; test flakes after 45 seconds with `mt/user-http-request` times out. And presumably other clients have similar;; issues. This ensures we give a good error message in this case.(with-open [server (non-responding-server)]- (with-redefs [geojson.settings/valid-geojson-url? (constantly true)]+ (mt/with-dynamic-fn-redefs [geojson.settings/valid-geojson-url? (constantly true)](let [never-responds-url (str "http://localhost:" (-port server))](testing "error is returned if URL connection fails"(is (= "GeoJSON URL failed to load"diff --git a/test/metabase/llm/anthropic_test.clj b/test/metabase/llm/anthropic_test.cljindex 00c9ba24faf..7285a15f9be 100644--- a/test/metabase/llm/anthropic_test.clj+++ b/test/metabase/llm/anthropic_test.clj@@ -106,7 +106,7 @@(deftest chat-completion-not-configured-test(testing "throws when API key not configured"- (with-redefs [llm.settings/llm-anthropic-api-key (constantly nil)]+ (mt/with-dynamic-fn-redefs [llm.settings/llm-anthropic-api-key (constantly nil)](is (thrown-with-msg?clojure.lang.ExceptionInfo#"not configured"@@ -125,7 +125,7 @@:output_tokens 250}}}](mt/with-temporary-setting-values [llm-anthropic-api-key "sk-ant-test-key"llm-anthropic-model "claude-sonnet-4-5-20250929"]- (with-redefs [http/post (constantly mock-response)]+ (mt/with-dynamic-fn-redefs [http/post (constantly mock-response)](let [result (anthropic/chat-completion {:system "You are a SQL expert":messages [{:role "user" :content "get all users"}]})](is (=? {:result {:sql "SELECT * FROM users"diff --git a/test/metabase/llm/api_test.clj b/test/metabase/llm/api_test.cljindex fa206b90a6e..af14ca67c23 100644--- a/test/metabase/llm/api_test.clj+++ b/test/metabase/llm/api_test.clj@@ -128,14 +128,14 @@(deftest generate-sql-error-handling-test(mt/with-temp [:model/Database db {:engine :postgres}](testing "403 when LLM not configured"- (with-redefs [llm.settings/llm-anthropic-api-key (constantly nil)]+ (mt/with-dynamic-fn-redefs [llm.settings/llm-anthropic-api-key (constantly nil)](let [response (mt/user-http-request :rasta :post 403 "llm/generate-sql"{:prompt "test":database_id (:id db)})](is (str/includes? (str response) "not configured")))))(testing "400 when no tables found"- (with-redefs [llm.settings/llm-anthropic-api-key (constantly "sk-ant-test")]+ (mt/with-dynamic-fn-redefs [llm.settings/llm-anthropic-api-key (constantly "sk-ant-test")](let [response (mt/user-http-request :rasta :post 400 "llm/generate-sql"{:prompt "no table mentions here":database_id (:id db)})]@@ -143,18 +143,18 @@(deftest list-models-unconfigured-test(testing "Returns 403 when LLM is not configured"- (with-redefs [metabot.settings/llm-metabot-configured? (constantly false)]+ (mt/with-dynamic-fn-redefs [metabot.settings/llm-metabot-configured? (constantly false)](let [response (mt/user-http-request :rasta :get 403 "llm/list-models")](is (str/includes? (str response) "not configured"))))))(deftest list-models-resolves-direct-provider-test(testing "resolves provider from provider-and-model and passes ai-proxy? = false"(let [captured (atom nil)]- (with-redefs [metabot.settings/llm-metabot-configured? (constantly true)- metabot.settings/llm-metabot-provider (constantly "anthropic/claude-sonnet-4")- metabot.self/list-models (fn [provider opts]- (reset! captured {:provider provider :opts opts})- {:models [{:id "claude-sonnet-4" :display_name "Claude Sonnet 4"}]})]+ (mt/with-dynamic-fn-redefs [metabot.settings/llm-metabot-configured? (constantly true)+ metabot.settings/llm-metabot-provider (constantly "anthropic/claude-sonnet-4")+ metabot.self/list-models (fn [provider opts]+ (reset! captured {:provider provider :opts opts})+ {:models [{:id "claude-sonnet-4" :display_name "Claude Sonnet 4"}]})](let [response (mt/user-http-request :rasta :get 200 "llm/list-models")](is (=? {:models [{:id "claude-sonnet-4":display_name "Claude Sonnet 4"}]}@@ -166,11 +166,11 @@(deftest list-models-resolves-metabase-prefixed-provider-test(testing "resolves inner provider from metabase/ prefix and passes ai-proxy? = true"(let [captured (atom nil)]- (with-redefs [metabot.settings/llm-metabot-configured? (constantly true)- metabot.settings/llm-metabot-provider (constantly "metabase/openrouter/anthropic/claude-haiku-4-5")- metabot.self/list-models (fn [provider opts]- (reset! captured {:provider provider :opts opts})- {:models [{:id "anthropic/claude-haiku-4-5" :display_name "Claude Haiku 4.5"}]})]+ (mt/with-dynamic-fn-redefs [metabot.settings/llm-metabot-configured? (constantly true)+ metabot.settings/llm-metabot-provider (constantly "metabase/openrouter/anthropic/claude-haiku-4-5")+ metabot.self/list-models (fn [provider opts]+ (reset! captured {:provider provider :opts opts})+ {:models [{:id "anthropic/claude-haiku-4-5" :display_name "Claude Haiku 4.5"}]})](let [response (mt/user-http-request :rasta :get 200 "llm/list-models")](is (=? {:models [{:id "anthropic/claude-haiku-4-5":display_name "Claude Haiku 4.5"}]}@@ -227,8 +227,8 @@:completion 200}:duration-ms 500}](snowplow-test/with-fake-snowplow-collector- (with-redefs [llm.settings/llm-anthropic-api-key (constantly "sk-ant-test")- llm.anthropic/chat-completion (constantly mock-chat-response)]+ (mt/with-dynamic-fn-redefs [llm.settings/llm-anthropic-api-key (constantly "sk-ant-test")+ llm.anthropic/chat-completion (constantly mock-chat-response)](let [response (mt/user-http-request :rasta :post 200 "llm/generate-sql"{:prompt "get all users":database_id (:id db)@@ -260,8 +260,8 @@:model/Table table {:db_id (:id db) :name "users" :schema "public"}:model/Field _ {:table_id (:id table) :name "id" :base_type :type/Integer}](snowplow-test/with-fake-snowplow-collector- (with-redefs [llm.settings/llm-anthropic-api-key (constantly "sk-ant-test")- llm.anthropic/chat-completion (fn [_] (throw (Exception. "API error")))]+ (mt/with-dynamic-fn-redefs [llm.settings/llm-anthropic-api-key (constantly "sk-ant-test")+ llm.anthropic/chat-completion (fn [_] (throw (Exception. "API error")))](mt/user-http-request :rasta :post 500 "llm/generate-sql"{:prompt "get all users":database_id (:id db)diff --git a/test/metabase/llm/settings_test.clj b/test/metabase/llm/settings_test.cljindex 739da0c36fb..4b80fe4f136 100644--- a/test/metabase/llm/settings_test.clj+++ b/test/metabase/llm/settings_test.clj@@ -32,7 +32,7 @@(deftest llm-anthropic-api-key-configured?-test(testing "returns false when no API key is set"- (with-redefs [llm.settings/llm-anthropic-api-key (constantly nil)]+ (mt/with-dynamic-fn-redefs [llm.settings/llm-anthropic-api-key (constantly nil)](is (false? (llm.settings/llm-anthropic-api-key-configured?)))))(testing "returns true when API key is set"diff --git a/test/metabase/llm/startup_test.clj b/test/metabase/llm/startup_test.cljindex dc9d290d85e..fb473c7a6e7 100644--- a/test/metabase/llm/startup_test.clj+++ b/test/metabase/llm/startup_test.clj@@ -13,12 +13,12 @@(deftest check-and-sync-settings-on-startup-syncs-legacy-metabot-default-test(mt/discard-setting-changes [llm-metabot-provider](mt/with-temporary-raw-setting-values [llm-metabot-provider nil]- (with-redefs [premium-features/canonically-has-feature?- (fn [feature]- (case feature- :metabot-v3 true- :metabase-ai-managed false))- metabot.settings/llm-metabot-configured? (constantly false)]+ (mt/with-dynamic-fn-redefs [premium-features/canonically-has-feature?+ (fn [feature]+ (case feature+ :metabot-v3 true+ :metabase-ai-managed false))+ metabot.settings/llm-metabot-configured? (constantly false)](llm.startup/check-and-sync-settings-on-startup!)(is (= metabot.settings/default-metabase-llm-metabot-provider(metabot.settings/llm-metabot-provider)))))))@@ -29,12 +29,12 @@(testing (format ":metabot-v3=%s :metabase-ai-managed=%s" legacy-result managed-result)(mt/discard-setting-changes [llm-metabot-provider](mt/with-temporary-raw-setting-values [llm-metabot-provider nil]- (with-redefs [premium-features/canonically-has-feature?- (fn [feature]- (case feature- :metabot-v3 legacy-result- :metabase-ai-managed managed-result))- metabot.settings/llm-metabot-configured? (constantly false)]+ (mt/with-dynamic-fn-redefs [premium-features/canonically-has-feature?+ (fn [feature]+ (case feature+ :metabot-v3 legacy-result+ :metabase-ai-managed managed-result))+ metabot.settings/llm-metabot-configured? (constantly false)](llm.startup/check-and-sync-settings-on-startup!)(is (= (case [legacy-result managed-result][true false] metabot.settings/default-metabase-llm-metabot-provider@@ -44,12 +44,12 @@(deftest check-and-sync-settings-on-startup-does-not-overwrite-configured-byok-test(mt/discard-setting-changes [llm-metabot-provider](mt/with-temporary-raw-setting-values [llm-metabot-provider nil]- (with-redefs [premium-features/canonically-has-feature?- (fn [feature]- (case feature- :metabot-v3 true- :metabase-ai-managed false))- metabot.settings/llm-metabot-configured? (constantly true)]+ (mt/with-dynamic-fn-redefs [premium-features/canonically-has-feature?+ (fn [feature]+ (case feature+ :metabot-v3 true+ :metabase-ai-managed false))+ metabot.settings/llm-metabot-configured? (constantly true)](llm.startup/check-and-sync-settings-on-startup!)(is (= metabot.settings/default-llm-metabot-provider(metabot.settings/llm-metabot-provider)))))))@@ -57,12 +57,12 @@(deftest check-and-sync-settings-on-startup-does-not-overwrite-explicit-provider-test(mt/discard-setting-changes [llm-metabot-provider](mt/with-temporary-setting-values [llm-metabot-provider "openai/gpt-4.1-mini"]- (with-redefs [premium-features/canonically-has-feature?- (fn [feature]- (case feature- :metabot-v3 true- :metabase-ai-managed false))- metabot.settings/llm-metabot-configured? (constantly false)]+ (mt/with-dynamic-fn-redefs [premium-features/canonically-has-feature?+ (fn [feature]+ (case feature+ :metabot-v3 true+ :metabase-ai-managed false))+ metabot.settings/llm-metabot-configured? (constantly false)](llm.startup/check-and-sync-settings-on-startup!)(is (= "openai/gpt-4.1-mini"(metabot.settings/llm-metabot-provider)))))))@@ -70,12 +70,12 @@(deftest check-and-sync-settings-on-startup-syncs-blank-provider-test(mt/discard-setting-changes [llm-metabot-provider](mt/with-temporary-raw-setting-values [llm-metabot-provider ""]- (with-redefs [premium-features/canonically-has-feature?- (fn [feature]- (case feature- :metabot-v3 true- :metabase-ai-managed false))- metabot.settings/llm-metabot-configured? (constantly false)]+ (mt/with-dynamic-fn-redefs [premium-features/canonically-has-feature?+ (fn [feature]+ (case feature+ :metabot-v3 true+ :metabase-ai-managed false))+ metabot.settings/llm-metabot-configured? (constantly false)](llm.startup/check-and-sync-settings-on-startup!)(is (= metabot.settings/default-metabase-llm-metabot-provider(metabot.settings/llm-metabot-provider)))))))diff --git a/test/metabase/login_history/api_test.clj b/test/metabase/login_history/api_test.cljindex 4c74f931d91..e6f703f82d9 100644--- a/test/metabase/login_history/api_test.clj+++ b/test/metabase/login_history/api_test.clj@@ -51,17 +51,17 @@:device_description windows-user-agent:ip_address "52.206.149.9"}];; Mock geocoding to avoid external GeoJS dependency- (with-redefs [req.util/geocode-ip-addresses- (fn [ip-addresses]- (into {}- (for [ip ip-addresses]- [ip (case ip- "185.233.100.23" {:description "Paris, France"- :timezone (t/zone-id "Europe/Paris")}- "52.206.149.9" {:description "Virginia, United States"- :timezone (t/zone-id "America/New_York")}- {:description "Unknown location"- :timezone nil})])))]+ (mt/with-dynamic-fn-redefs [req.util/geocode-ip-addresses+ (fn [ip-addresses]+ (into {}+ (for [ip ip-addresses]+ [ip (case ip+ "185.233.100.23" {:description "Paris, France"+ :timezone (t/zone-id "Europe/Paris")}+ "52.206.149.9" {:description "Virginia, United States"+ :timezone (t/zone-id "America/New_York")}+ {:description "Unknown location"+ :timezone nil})])))](is (malli= [:cat;; localhost ipv6[:mapdiff --git a/test/metabase/metabot/agent/core_test.clj b/test/metabase/metabot/agent/core_test.cljindex 5448b90b513..6fd92f5d0c3 100644--- a/test/metabase/metabot/agent/core_test.clj+++ b/test/metabase/metabot/agent/core_test.clj@@ -57,9 +57,9 @@(mt/as-admin(mt/with-temporary-setting-values [llm-metabot-provider test-provider](testing "runs agent loop with mocked LLM returning text"- (with-redefs [openrouter/openrouter (fn [_]- (mut/mock-llm-response- [{:type :text :text "Hello"}]))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter (fn [_]+ (mut/mock-llm-response+ [{:type :text :text "Hello"}]))](let [result (into [] (agent/run-agent-loop{:messages [{:role :user :content "Hi"}]:state {}@@ -73,10 +73,10 @@(testing "sql profile requests required tool choice"(let [captured (atom nil)]- (with-redefs [self/call-llm (fn [_model _system _parts _tools _tracking-opts llm-opts]- (reset! captured llm-opts)- (mut/mock-llm-response- [{:type :text :text "Hello"}]))]+ (mt/with-dynamic-fn-redefs [self/call-llm (fn [_model _system _parts _tools _tracking-opts llm-opts]+ (reset! captured llm-opts)+ (mut/mock-llm-response+ [{:type :text :text "Hello"}]))](into [] (agent/run-agent-loop{:messages [{:role :user :content "Hi"}]:state {}@@ -86,17 +86,17 @@(testing "runs agent loop with tool execution"(let [call-count (atom 0)]- (with-redefs [openrouter/openrouter (fn [_]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter (fn [_];; First call returns tool-input, second returns text- (let [n (swap! call-count inc)]- (if (= 1 n)- (mut/mock-llm-response- [{:type :tool-input- :id "t1"- :function "search"- :arguments {:query "test"}}])- (mut/mock-llm-response- [{:type :text :text "Found results"}]))))]+ (let [n (swap! call-count inc)]+ (if (= 1 n)+ (mut/mock-llm-response+ [{:type :tool-input+ :id "t1"+ :function "search"+ :arguments {:query "test"}}])+ (mut/mock-llm-response+ [{:type :text :text "Found results"}]))))](let [result (into [] (agent/run-agent-loop{:messages [{:role :user :content "Search for test"}]:state {}@@ -110,8 +110,8 @@(is (some #(= :tool-input (:type %)) result))))))(testing "handles errors gracefully"- (with-redefs [openrouter/openrouter (fn [_]- (throw (ex-info "Mock error" {})))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter (fn [_]+ (throw (ex-info "Mock error" {})))](let [result (mt/with-log-level [metabase.metabot.agent.core :fatal](into [] (agent/run-agent-loop{:messages [{:role :user :content "Hi"}]@@ -153,9 +153,9 @@(mt/as-admin(mt/with-temporary-setting-values [llm-metabot-provider test-provider](testing "runs full agent loop without external calls"- (with-redefs [openrouter/openrouter (fn [_]- (mut/mock-llm-response- [{:type :text :text "Test response"}]))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter (fn [_]+ (mut/mock-llm-response+ [{:type :text :text "Test response"}]))](let [result (into [] (agent/run-agent-loop{:messages [{:role :user :content "Hello"}]:state {}@@ -296,16 +296,16 @@{:type :usage :usage {:promptTokens 300 :completionTokens 10} :model "test" :id "msg-3"}]]];; Mock only openrouter/openrouter (LLM) and metabot-search/search (search backend);; Everything else runs real code- (with-redefs [openrouter/openrouter (fn [_opts]- (let [n (swap! llm-call-count inc)]- (mut/mock-llm-response (get llm-responses (dec n) []))))- metabot-search/search (fn [_args]- [{:id orders-table-id- :type "table"- :name "orders"- :display_name "Orders"- :description "This is a confirmed order for a product from a user."- :database_id (mt/id)}])]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter (fn [_opts]+ (let [n (swap! llm-call-count inc)]+ (mut/mock-llm-response (get llm-responses (dec n) []))))+ metabot-search/search (fn [_args]+ [{:id orders-table-id+ :type "table"+ :name "orders"+ :display_name "Orders"+ :description "This is a confirmed order for a product from a user."+ :database_id (mt/id)}])](testing "Should successfully go through 3 iterations"(is (=? [{:type :start}{:type :tool-input :function "search"}@@ -349,25 +349,25 @@(mt/with-temporary-setting-values [llm-metabot-provider test-provider](testing "usage parts are cumulative across agent loop iterations"(let [call-count (atom 0)]- (with-redefs [openrouter/openrouter- (fn [_]- (let [n (swap! call-count inc)]- (case (int n)+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (fn [_]+ (let [n (swap! call-count inc)]+ (case (int n);; Iteration 1: tool call with usage- 1 (mut/mock-llm-response- [{:type :start :id "msg-1"}- {:type :tool-input- :id "t1"- :function "search"- :arguments {:query "test"}}- {:type :usage :usage {:promptTokens 100 :completionTokens 20}- :model "gpt-4" :id "msg-1"}])+ 1 (mut/mock-llm-response+ [{:type :start :id "msg-1"}+ {:type :tool-input+ :id "t1"+ :function "search"+ :arguments {:query "test"}}+ {:type :usage :usage {:promptTokens 100 :completionTokens 20}+ :model "gpt-4" :id "msg-1"}]);; Iteration 2: text response with usage- (mut/mock-llm-response- [{:type :start :id "msg-2"}- {:type :text :text "Done"}- {:type :usage :usage {:promptTokens 150 :completionTokens 30}- :model "gpt-4" :id "msg-2"}]))))]+ (mut/mock-llm-response+ [{:type :start :id "msg-2"}+ {:type :text :text "Done"}+ {:type :usage :usage {:promptTokens 150 :completionTokens 30}+ :model "gpt-4" :id "msg-2"}]))))](let [result (mt/with-log-level [metabase.metabot.agent.core :warn](into [] (agent/run-agent-loop{:messages [{:role :user :content "test"}]@@ -386,23 +386,23 @@(testing "cumulative usage works across multiple models"(let [call-count (atom 0)]- (with-redefs [openrouter/openrouter- (fn [_]- (let [n (swap! call-count inc)]- (case (int n)- 1 (mut/mock-llm-response- [{:type :start :id "msg-1"}- {:type :tool-input- :id "t1"- :function "search"- :arguments {:query "test"}}- {:type :usage :usage {:promptTokens 100 :completionTokens 20}- :model "model-a" :id "msg-1"}])- (mut/mock-llm-response- [{:type :start :id "msg-2"}- {:type :text :text "Done"}- {:type :usage :usage {:promptTokens 200 :completionTokens 40}- :model "model-b" :id "msg-2"}]))))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (fn [_]+ (let [n (swap! call-count inc)]+ (case (int n)+ 1 (mut/mock-llm-response+ [{:type :start :id "msg-1"}+ {:type :tool-input+ :id "t1"+ :function "search"+ :arguments {:query "test"}}+ {:type :usage :usage {:promptTokens 100 :completionTokens 20}+ :model "model-a" :id "msg-1"}])+ (mut/mock-llm-response+ [{:type :start :id "msg-2"}+ {:type :text :text "Done"}+ {:type :usage :usage {:promptTokens 200 :completionTokens 40}+ :model "model-b" :id "msg-2"}]))))](let [result (mt/with-log-level [metabase.metabot.agent.core :warn](into [] (agent/run-agent-loop{:messages [{:role :user :content "test"}]@@ -424,13 +424,13 @@(mt/with-temporary-setting-values [llm-metabot-provider test-provider](testing "agent loop retries when LLM returns 429 and then succeeds"(let [call-count (atom 0)]- (with-redefs [self/retry-delay-ms (constantly 0)- openrouter/openrouter (fn [_]- (if (< (swap! call-count inc) 2)- (throw (ex-info "Anthropic API has rate limited us"- {:status 429 :api-error true}))- (mut/mock-llm-response- [{:type :text :text "Hello after retry"}])))]+ (mt/with-dynamic-fn-redefs [self/retry-delay-ms (constantly 0)+ openrouter/openrouter (fn [_]+ (if (< (swap! call-count inc) 2)+ (throw (ex-info "Anthropic API has rate limited us"+ {:status 429 :api-error true}))+ (mut/mock-llm-response+ [{:type :text :text "Hello after retry"}])))](is (=? [{:type :text :text "Hello after retry"}{:type :data :data-type "state"}](mt/with-log-level [metabase.metabot.self :fatal]@@ -451,17 +451,17 @@(mt/with-prometheus-system! [_ system](testing "records agent-requests, agent-iterations, and llm-requests metrics"(let [call-count (atom 0)]- (with-redefs [openrouter/openrouter- (fn [_]- (let [n (swap! call-count inc)]- (if (= 1 n)- (mut/mock-llm-response- [{:type :tool-input- :id "t1"- :function "search"- :arguments {:query "test"}}])- (mut/mock-llm-response- [{:type :text :text "Done"}]))))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (fn [_]+ (let [n (swap! call-count inc)]+ (if (= 1 n)+ (mut/mock-llm-response+ [{:type :tool-input+ :id "t1"+ :function "search"+ :arguments {:query "test"}}])+ (mut/mock-llm-response+ [{:type :text :text "Done"}]))))](mt/with-log-level [metabase.metabot.agent.core :warn](run-agent-loop! {:messages [{:role :user :content "test"}]:state {}@@ -489,7 +489,7 @@(analytics/clear! :metabase-metabot/llm-requests)(testing "records agent-errors on failure"- (with-redefs [openrouter/openrouter (fn [_] (throw (ex-info "boom" {})))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter (fn [_] (throw (ex-info "boom" {})))](mt/with-log-level [metabase.metabot.agent.core :fatal](run-agent-loop! {:messages [{:role :user :content "test"}]:state {}@@ -516,27 +516,27 @@(testing "fires :snowplow/ai_service_event 'agent_used_tool' per tool call"(let [call-count (atom 0)rasta-id (mt/user->id :rasta)]- (with-redefs [openrouter/openrouter- (fn [_]- (let [n (swap! call-count inc)]- (if (= 1 n)- (mut/mock-llm-response- [{:type :start :id "msg-1"}- {:type :tool-input- :id "t1"- :function "search"- :arguments {:semantic_queries ["test"]- :keyword_queries ["test"]- :entity_types ["table"]}}- {:type :usage :usage {:promptTokens 100 :completionTokens 20}- :model "test-model" :id "msg-1"}])- (mut/mock-llm-response- [{:type :start :id "msg-2"}- {:type :text :text "Done"}- {:type :usage :usage {:promptTokens 150 :completionTokens 30}- :model "test-model" :id "msg-2"}]))))- metabot-search/search- (fn [_args] [{:id 1 :type "table" :name "test" :display_name "Test" :database_id 1}])]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (fn [_]+ (let [n (swap! call-count inc)]+ (if (= 1 n)+ (mut/mock-llm-response+ [{:type :start :id "msg-1"}+ {:type :tool-input+ :id "t1"+ :function "search"+ :arguments {:semantic_queries ["test"]+ :keyword_queries ["test"]+ :entity_types ["table"]}}+ {:type :usage :usage {:promptTokens 100 :completionTokens 20}+ :model "test-model" :id "msg-1"}])+ (mut/mock-llm-response+ [{:type :start :id "msg-2"}+ {:type :text :text "Done"}+ {:type :usage :usage {:promptTokens 150 :completionTokens 30}+ :model "test-model" :id "msg-2"}]))))+ metabot-search/search+ (fn [_args] [{:id 1 :type "table" :name "test" :display_name "Test" :database_id 1}])](mt/with-log-level [metabase.metabot.agent.core :warn](mt/with-current-user rasta-id(snowplow-test/with-fake-snowplow-collector@@ -562,25 +562,25 @@(testing "fires 'agent_used_tool' with result=error when tool fails"(let [call-count (atom 0)rasta-id (mt/user->id :rasta)]- (with-redefs [openrouter/openrouter- (fn [_]- (let [n (swap! call-count inc)]- (if (= 1 n)- (mut/mock-llm-response- [{:type :start :id "msg-1"}- {:type :tool-input- :id "t1"- :function "search"- :arguments {:bad-arg "wrong"}}- {:type :usage :usage {:promptTokens 100 :completionTokens 20}- :model "test-model" :id "msg-1"}])- (mut/mock-llm-response- [{:type :start :id "msg-2"}- {:type :text :text "Done"}- {:type :usage :usage {:promptTokens 150 :completionTokens 30}- :model "test-model" :id "msg-2"}]))))- metabot-search/search- (fn [_args] (throw (ex-info "should not be called" {})))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (fn [_]+ (let [n (swap! call-count inc)]+ (if (= 1 n)+ (mut/mock-llm-response+ [{:type :start :id "msg-1"}+ {:type :tool-input+ :id "t1"+ :function "search"+ :arguments {:bad-arg "wrong"}}+ {:type :usage :usage {:promptTokens 100 :completionTokens 20}+ :model "test-model" :id "msg-1"}])+ (mut/mock-llm-response+ [{:type :start :id "msg-2"}+ {:type :text :text "Done"}+ {:type :usage :usage {:promptTokens 150 :completionTokens 30}+ :model "test-model" :id "msg-2"}]))))+ metabot-search/search+ (fn [_args] (throw (ex-info "should not be called" {})))](mt/with-log-level [metabase.metabot.agent.core :warn](mt/with-current-user rasta-id(snowplow-test/with-fake-snowplow-collector@@ -600,23 +600,23 @@(testing "fires :snowplow/token_usage event per LLM call"(let [call-count (atom 0)rasta-id (mt/user->id :rasta)]- (with-redefs [openrouter/openrouter- (fn [_]- (let [n (swap! call-count inc)]- (if (= 1 n)- (mut/mock-llm-response- [{:type :start :id "msg-1"}- {:type :tool-input- :id "t1"- :function "search"- :arguments {:query "test"}}- {:type :usage :usage {:promptTokens 100 :completionTokens 20}- :model "test-model" :id "msg-1"}])- (mut/mock-llm-response- [{:type :start :id "msg-2"}- {:type :text :text "Done"}- {:type :usage :usage {:promptTokens 150 :completionTokens 30}- :model "test-model" :id "msg-2"}]))))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (fn [_]+ (let [n (swap! call-count inc)]+ (if (= 1 n)+ (mut/mock-llm-response+ [{:type :start :id "msg-1"}+ {:type :tool-input+ :id "t1"+ :function "search"+ :arguments {:query "test"}}+ {:type :usage :usage {:promptTokens 100 :completionTokens 20}+ :model "test-model" :id "msg-1"}])+ (mut/mock-llm-response+ [{:type :start :id "msg-2"}+ {:type :text :text "Done"}+ {:type :usage :usage {:promptTokens 150 :completionTokens 30}+ :model "test-model" :id "msg-2"}]))))](mt/with-log-level [metabase.metabot.agent.core :warn](mt/with-current-user rasta-id(snowplow-test/with-fake-snowplow-collectordiff --git a/test/metabase/metabot/agent/profiles_test.clj b/test/metabase/metabot/agent/profiles_test.cljindex bc3f1754ab4..3873c0158e7 100644--- a/test/metabase/metabot/agent/profiles_test.clj+++ b/test/metabase/metabot/agent/profiles_test.clj@@ -180,47 +180,47 @@(is (contains? tools "navigate_user"))))))(deftest transform-feature-capabilities-test- (let [orig-has-feature premium-features/has-feature?+ (let [orig-has-feature (mt/original-fn #'premium-features/has-feature?)transform-tools #{#'tools.transforms/write-transform-sql-tool#'tools.transforms/write-transform-python-tool}](testing "Available with features present"- (with-redefs [premium-features/has-feature? (fn [feat]- (if (#{:transforms-basic :transforms-python} feat)- true- (orig-has-feature feat)))]+ (mt/with-dynamic-fn-redefs [premium-features/has-feature? (fn [feat]+ (if (#{:transforms-basic :transforms-python} feat)+ true+ (orig-has-feature feat)))](is (= transform-tools(set (#'profiles/filter-by-capabilities transform-tools["permission:write_transforms"]))))))(testing "Not available with missing features"- (with-redefs [premium-features/is-hosted? (constantly true)- premium-features/has-feature? (fn [feat]- (if (#{:transforms-basic :transforms-python} feat)- false- (orig-has-feature feat)))]+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly true)+ premium-features/has-feature? (fn [feat]+ (if (#{:transforms-basic :transforms-python} feat)+ false+ (orig-has-feature feat)))](is (= #{}(set (#'profiles/filter-by-capabilities transform-tools["permission:write_transforms"]))))))(testing "Sql tool available on self hosted instances"- (with-redefs [premium-features/is-hosted? (constantly false)- premium-features/has-feature? (fn [feat]- (if (#{:transforms-basic :transforms-python} feat)- false- (orig-has-feature feat)))]+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly false)+ premium-features/has-feature? (fn [feat]+ (if (#{:transforms-basic :transforms-python} feat)+ false+ (orig-has-feature feat)))](is (= #{#'tools.transforms/write-transform-sql-tool}(set (#'profiles/filter-by-capabilities transform-tools["permission:write_transforms"]))))))(testing "Python transform tools not available when basic transforms are not available"- (with-redefs [premium-features/is-hosted? (constantly true)- premium-features/has-feature? (fn [feat]- (cond- (#{:transforms-basic} feat)- false+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly true)+ premium-features/has-feature? (fn [feat]+ (cond+ (#{:transforms-basic} feat)+ false- (#{:transforms-python} feat)- true+ (#{:transforms-python} feat)+ true- :else- (orig-has-feature feat)))]+ :else+ (orig-has-feature feat)))](is (= #{}(set (#'profiles/filter-by-capabilities transform-tools["permission:write_transforms"]))))))))diff --git a/test/metabase/metabot/agent/user_context_test.clj b/test/metabase/metabot/agent/user_context_test.cljindex 14f4fafe79c..bc4764d7ba5 100644--- a/test/metabase/metabot/agent/user_context_test.clj+++ b/test/metabase/metabot/agent/user_context_test.clj@@ -258,11 +258,11 @@(deftest format-current-user-info-test(testing "formats the current user as XML"- (with-redefs [entity-details/get-current-user (fn [_]- {:structured-output {:id 1- :name "Jane Doe"- :email-address "[email protected]"- :glossary {"ARR" "Annual Recurring Revenue"}}})]+ (mt/with-dynamic-fn-redefs [entity-details/get-current-user (fn [_]+ {:structured-output {:id 1+ :name "Jane Doe"+ :email-address "[email protected]"+ :glossary {"ARR" "Annual Recurring Revenue"}}})](is (= (llm-rep/user->xml {:id 1:name "Jane Doe":email "[email protected]"@@ -270,13 +270,13 @@(user-context/format-current-user-info {})))))(testing "returns nil when there is no current user"- (with-redefs [entity-details/get-current-user (fn [_]- {:output "current user not found"})]+ (mt/with-dynamic-fn-redefs [entity-details/get-current-user (fn [_]+ {:output "current user not found"})](is (nil? (user-context/format-current-user-info {}))))))(deftest enrich-context-for-template-test(testing "enriches context with all template variables (legacy type: native)"- (with-redefs [user-context/format-current-user-info (constantly "<user>Jane Doe</user>")]+ (mt/with-dynamic-fn-redefs [user-context/format-current-user-info (constantly "<user>Jane Doe</user>")](let [context {:current_time_with_timezone "2024-01-15T14:30:00-05:00":first_day_of_week "Monday":user_is_viewing [{:type "adhoc"@@ -329,24 +329,24 @@(deftest format-entity-includes-measures-and-segments-test(testing "table viewing context includes measures and segments when present"- (with-redefs [entity-details/get-table-details- (fn [{:keys [table-id with-measures? with-segments?]}]+ (mt/with-dynamic-fn-redefs [entity-details/get-table-details+ (fn [{:keys [table-id with-measures? with-segments?]}];; Verify that with-measures? and with-segments? are requested- (is (true? with-measures?) "should request measures")- (is (true? with-segments?) "should request segments")- {:structured-output- {:id table-id- :type :table- :name "int_shopify_order_facts"- :database_id 2- :database_engine "postgres"- :database_schema "shopify_enriched"- :description "Order facts with enriched data"- :fields [{:field_id "t10-1" :name "order_id" :database_type "INTEGER"}]- :measures [{:id 1 :name "avg_order_value" :display-name "Average Order Value"- :description "Average value of all orders"}]- :segments [{:id 2 :name "q4_orders" :display-name "Q4 Orders"- :description "Orders placed in Q4"}]}})]+ (is (true? with-measures?) "should request measures")+ (is (true? with-segments?) "should request segments")+ {:structured-output+ {:id table-id+ :type :table+ :name "int_shopify_order_facts"+ :database_id 2+ :database_engine "postgres"+ :database_schema "shopify_enriched"+ :description "Order facts with enriched data"+ :fields [{:field_id "t10-1" :name "order_id" :database_type "INTEGER"}]+ :measures [{:id 1 :name "avg_order_value" :display-name "Average Order Value"+ :description "Average value of all orders"}]+ :segments [{:id 2 :name "q4_orders" :display-name "Q4 Orders"+ :description "Orders placed in Q4"}]}})](let [result (user-context/format-viewing-context{:user_is_viewing [{:type "table" :id 10}]})](is (re-find #"table" result))@@ -357,21 +357,21 @@(is (re-find #"Q4 Orders" result)))))(testing "model viewing context includes measures and segments when present"- (with-redefs [entity-details/get-table-details- (fn [{:keys [model-id with-measures? with-segments?]}]- (is (true? with-measures?) "should request measures for model")- (is (true? with-segments?) "should request segments for model")- {:structured-output- {:id model-id- :type :model- :name "Revenue Model"- :database_id 2- :database_engine "postgres"- :description "Revenue model"- :measures [{:id 3 :name "total_revenue" :display-name "Total Revenue"- :description "Sum of all revenue"}]- :segments [{:id 4 :name "enterprise" :display-name "Enterprise Accounts"- :description "Enterprise-tier customers"}]}})]+ (mt/with-dynamic-fn-redefs [entity-details/get-table-details+ (fn [{:keys [model-id with-measures? with-segments?]}]+ (is (true? with-measures?) "should request measures for model")+ (is (true? with-segments?) "should request segments for model")+ {:structured-output+ {:id model-id+ :type :model+ :name "Revenue Model"+ :database_id 2+ :database_engine "postgres"+ :description "Revenue model"+ :measures [{:id 3 :name "total_revenue" :display-name "Total Revenue"+ :description "Sum of all revenue"}]+ :segments [{:id 4 :name "enterprise" :display-name "Enterprise Accounts"+ :description "Enterprise-tier customers"}]}})](let [result (user-context/format-viewing-context{:user_is_viewing [{:type "model" :id 20}]})](is (re-find #"model" result))@@ -382,16 +382,16 @@(is (re-find #"Enterprise Accounts" result)))))(testing "table viewing context omits measures/segments sections when none exist"- (with-redefs [entity-details/get-table-details- (fn [{:keys [entity-id]}]- {:structured-output- {:id entity-id- :type :table- :name "plain_table"- :database_id 1- :database_engine "h2"- :description "A plain table"- :fields [{:field_id "t1-1" :name "id" :database_type "INTEGER"}]}})]+ (mt/with-dynamic-fn-redefs [entity-details/get-table-details+ (fn [{:keys [entity-id]}]+ {:structured-output+ {:id entity-id+ :type :table+ :name "plain_table"+ :database_id 1+ :database_engine "h2"+ :description "A plain table"+ :fields [{:field_id "t1-1" :name "id" :database_type "INTEGER"}]}})](let [result (user-context/format-viewing-context{:user_is_viewing [{:type "table" :id 1}]})](is (re-find #"plain_table" result))diff --git a/test/metabase/metabot/api/document_test.clj b/test/metabase/metabot/api/document_test.cljindex e4763cdc716..950f2de7ee7 100644--- a/test/metabase/metabot/api/document_test.clj+++ b/test/metabase/metabot/api/document_test.clj@@ -16,13 +16,13 @@(deftest generate-content-backwards-compatible-route-test(mt/with-temporary-setting-values [llm-metabot-provider test-provider]- (with-redefs [openrouter/openrouter- (fn [_]- (mut/mock-llm-response- [{:type :start :id "msg-1"}- {:type :text :text "No chart available"}- {:type :usage :usage {:promptTokens 100 :completionTokens 20}- :model "test-model" :id "msg-1"}]))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (fn [_]+ (mut/mock-llm-response+ [{:type :start :id "msg-1"}+ {:type :text :text "No chart available"}+ {:type :usage :usage {:promptTokens 100 :completionTokens 20}+ :model "test-model" :id "msg-1"}]))](is (= {:draft_card nil:description nil:error "No chart available"}@@ -33,13 +33,13 @@(deftest generate-content-prometheus-test(mt/with-temporary-setting-values [llm-metabot-provider test-provider](mt/with-prometheus-system! [_ system]- (with-redefs [openrouter/openrouter- (fn [_]- (mut/mock-llm-response- [{:type :start :id "msg-1"}- {:type :text :text "No chart available"}- {:type :usage :usage {:promptTokens 100 :completionTokens 20}- :model "anthropic/claude-haiku-4-5" :id "msg-1"}]))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (fn [_]+ (mut/mock-llm-response+ [{:type :start :id "msg-1"}+ {:type :text :text "No chart available"}+ {:type :usage :usage {:promptTokens 100 :completionTokens 20}+ :model "anthropic/claude-haiku-4-5" :id "msg-1"}]))](mt/user-http-request :crowberto:post 200 "metabot/document/generate-content"{:instructions "Show me sales data"}))@@ -58,13 +58,13 @@(mt/with-temporary-setting-values [llm-metabot-provider test-provider](binding [scope/*current-user-metabot-permissions* scope/all-yes-permissions](let [rasta-id (mt/user->id :rasta)]- (with-redefs [openrouter/openrouter- (fn [_]- (mut/mock-llm-response- [{:type :start :id "msg-1"}- {:type :text :text "No chart available"}- {:type :usage :usage {:promptTokens 100 :completionTokens 20}- :model "anthropic/claude-haiku-4-5" :id "msg-1"}]))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (fn [_]+ (mut/mock-llm-response+ [{:type :start :id "msg-1"}+ {:type :text :text "No chart available"}+ {:type :usage :usage {:promptTokens 100 :completionTokens 20}+ :model "anthropic/claude-haiku-4-5" :id "msg-1"}]))](snowplow-test/with-fake-snowplow-collector(mt/user-http-request :rasta:post 200 "metabot/document/generate-content"diff --git a/test/metabase/metabot/api/entity_analysis_test.clj b/test/metabase/metabot/api/entity_analysis_test.cljindex cd815fe438a..c6d471b5728 100644--- a/test/metabase/metabot/api/entity_analysis_test.clj+++ b/test/metabase/metabot/api/entity_analysis_test.clj@@ -8,7 +8,7 @@(deftest analyze-chart-test(testing "POST /api/ai-entity-analysis/analyze-chart"- (with-redefs [metabot/analyze-chart (constantly {:analysis "This chart shows a steady increase in sales over time, with a notable peak in Q4."})]+ (mt/with-dynamic-fn-redefs [metabot/analyze-chart (constantly {:analysis "This chart shows a steady increase in sales over time, with a notable peak in Q4."})](let [response (mt/user-http-request :rasta :post 200 "ai-entity-analysis/analyze-chart"{:image_base64 "base64encodedimage":name "Sales Trend"@@ -22,12 +22,12 @@(deftest analyze-chart-returns-free-trial-limit-error-when-managed-provider-is-locked-test(mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider"metabase/anthropic/claude-sonnet-4-6"]- (with-redefs [premium-features/token-status- (constantly {:meters {:anthropic:claude-sonnet-4-6:tokens {:meter-value 1000000- :is-locked true}}})- metabot/analyze-chart- (fn [& _]- (throw (ex-info "should not call analyze-chart" {})))]+ (mt/with-dynamic-fn-redefs [premium-features/token-status+ (constantly {:meters {:anthropic:claude-sonnet-4-6:tokens {:meter-value 1000000+ :is-locked true}}})+ metabot/analyze-chart+ (fn [& _]+ (throw (ex-info "should not call analyze-chart" {})))](let [response (mt/user-http-request :rasta :post 402 "ai-entity-analysis/analyze-chart"{:image_base64 "base64encodedimage":name "Sales Trend"diff --git a/test/metabase/metabot/api/metabot_test.clj b/test/metabase/metabot/api/metabot_test.cljindex d71e7164e25..e3300788f96 100644--- a/test/metabase/metabot/api/metabot_test.clj+++ b/test/metabase/metabot/api/metabot_test.clj@@ -215,7 +215,7 @@:collection_id collection-id-1}](testing "should update use_verified_content field"- (with-redefs [metabot.suggested-prompts/generate-sample-prompts (constantly nil)]+ (mt/with-dynamic-fn-redefs [metabot.suggested-prompts/generate-sample-prompts (constantly nil)](let [response (mt/user-http-request :crowberto :put 200(format "metabot/metabot/%d" metabot-id){:use_verified_content true})]@@ -226,7 +226,7 @@(is (true? (:use_verified_content updated-metabot)))))))(testing "should update collection_id field"- (with-redefs [metabot.suggested-prompts/generate-sample-prompts (constantly nil)]+ (mt/with-dynamic-fn-redefs [metabot.suggested-prompts/generate-sample-prompts (constantly nil)](let [response (mt/user-http-request :crowberto :put 200(format "metabot/metabot/%d" metabot-id){:collection_id collection-id-2})]@@ -237,7 +237,7 @@(is (= collection-id-2 (:collection_id updated-metabot)))))))(testing "should update collection_id to null"- (with-redefs [metabot.suggested-prompts/generate-sample-prompts (constantly nil)]+ (mt/with-dynamic-fn-redefs [metabot.suggested-prompts/generate-sample-prompts (constantly nil)](let [response (mt/user-http-request :crowberto :put 200(format "metabot/metabot/%d" metabot-id){:collection_id nil})]@@ -247,7 +247,7 @@(is (= nil (:collection_id updated-metabot)))))))(testing "should update all fields simultaneously"- (with-redefs [metabot.suggested-prompts/generate-sample-prompts (constantly nil)]+ (mt/with-dynamic-fn-redefs [metabot.suggested-prompts/generate-sample-prompts (constantly nil)](let [response (mt/user-http-request :crowberto :put 200(format "metabot/metabot/%d" metabot-id){:use_verified_content false@@ -289,15 +289,15 @@:prompt "existing prompt":model :model:card_id card-id}]- (with-redefs [premium-features/token-status- (constantly {:meters {:anthropic:claude-sonnet-4-6:tokens {:meter-value 1000000- :is-locked true}}})- metabot.suggested-prompts/delete-all-metabot-prompts- (fn [& _]- (throw (ex-info "should not delete prompts" {})))- metabot.suggested-prompts/generate-sample-prompts- (fn [& _]- (throw (ex-info "should not generate prompts" {})))]+ (mt/with-dynamic-fn-redefs [premium-features/token-status+ (constantly {:meters {:anthropic:claude-sonnet-4-6:tokens {:meter-value 1000000+ :is-locked true}}})+ metabot.suggested-prompts/delete-all-metabot-prompts+ (fn [& _]+ (throw (ex-info "should not delete prompts" {})))+ metabot.suggested-prompts/generate-sample-prompts+ (fn [& _]+ (throw (ex-info "should not generate prompts" {})))](let [response (mt/user-http-request :crowberto :put 200(format "metabot/metabot/%d" metabot-id){:collection_id nil})]@@ -318,15 +318,15 @@:prompt "existing prompt":model :model:card_id card-id}]- (with-redefs [premium-features/token-status- (constantly {:meters {:anthropic:claude-sonnet-4-6:tokens {:meter-value 1000000- :is-locked true}}})- metabot.suggested-prompts/delete-all-metabot-prompts- (fn [& _]- (throw (ex-info "should not delete prompts" {})))- metabot.suggested-prompts/generate-sample-prompts- (fn [& _]- (throw (ex-info "should not generate prompts" {})))]+ (mt/with-dynamic-fn-redefs [premium-features/token-status+ (constantly {:meters {:anthropic:claude-sonnet-4-6:tokens {:meter-value 1000000+ :is-locked true}}})+ metabot.suggested-prompts/delete-all-metabot-prompts+ (fn [& _]+ (throw (ex-info "should not delete prompts" {})))+ metabot.suggested-prompts/generate-sample-prompts+ (fn [& _]+ (throw (ex-info "should not generate prompts" {})))](let [response (mt/user-http-request :crowberto :post 402(format "metabot/metabot/%d/prompt-suggestions/regenerate" metabot-id))](is (= "You've used all of your included AI service tokens. To keep using AI features, end your trial early and start your subscription, or add your own AI provider API key."@@ -372,12 +372,12 @@(let [original-prompt-ids #{prompt-id-1 prompt-id-2}](testing "should regenerate prompts when use_verified_content changes"- (with-redefs [metabot.suggested-prompts/generate-sample-prompts- (fn [metabot-id]- (t2/insert! :model/MetabotPrompt {:metabot_id metabot-id- :prompt "new prompt after verified change"- :model :metric- :card_id card-id-3}))]+ (mt/with-dynamic-fn-redefs [metabot.suggested-prompts/generate-sample-prompts+ (fn [metabot-id]+ (t2/insert! :model/MetabotPrompt {:metabot_id metabot-id+ :prompt "new prompt after verified change"+ :model :metric+ :card_id card-id-3}))](mt/user-http-request :crowberto :put 200(format "metabot/metabot/%d" metabot-id){:use_verified_content true})@@ -390,12 +390,12 @@(is (= "new prompt after verified change" (:prompt (first current-prompts)))))))(testing "should regenerate prompts when collection_id changes"- (with-redefs [metabot.suggested-prompts/generate-sample-prompts- (fn [metabot-id]- (t2/insert! :model/MetabotPrompt {:metabot_id metabot-id- :prompt "new prompt after collection change"- :model :model- :card_id card-id-4}))]+ (mt/with-dynamic-fn-redefs [metabot.suggested-prompts/generate-sample-prompts+ (fn [metabot-id]+ (t2/insert! :model/MetabotPrompt {:metabot_id metabot-id+ :prompt "new prompt after collection change"+ :model :model+ :card_id card-id-4}))](mt/user-http-request :crowberto :put 200(format "metabot/metabot/%d" metabot-id){:collection_id collection-id-2})@@ -417,8 +417,8 @@;; Make a PUT request that doesn't change verified content or collection_id;; (This would be if we add other fields to update in the future)- (with-redefs [metabot.suggested-prompts/generate-sample-prompts- (fn [_] (throw (Exception. "Should not be called")))]+ (mt/with-dynamic-fn-redefs [metabot.suggested-prompts/generate-sample-prompts+ (fn [_] (throw (Exception. "Should not be called")))](mt/user-http-request :crowberto :put 200(format "metabot/metabot/%d" metabot-id){:use_verified_content true ; Same as current valuediff --git a/test/metabase/metabot/api_test.clj b/test/metabase/metabot/api_test.cljindex 9ed7d599ce8..3c4b9e02c19 100644--- a/test/metabase/metabot/api_test.clj+++ b/test/metabase/metabot/api_test.clj@@ -43,12 +43,12 @@(let [conversation-id (str (random-uuid))question {:role "user" :content "Test native streaming"}historical-message {:role "user" :content "previous message"}]- (with-redefs [openrouter/openrouter (fn [_]- (mut/mock-llm-response- [{:type :start :id "msg-1"}- {:type :text :text "Hello from native agent!"}- {:type :usage :usage {:promptTokens 10 :completionTokens 5}- :model "test-model" :id "msg-1"}]))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter (fn [_]+ (mut/mock-llm-response+ [{:type :start :id "msg-1"}+ {:type :text :text "Hello from native agent!"}+ {:type :usage :usage {:promptTokens 10 :completionTokens 5}+ :model "test-model" :id "msg-1"}]))](testing "Native agent streaming request"(mt/with-model-cleanup [:model/MetabotMessage[:model/MetabotConversation :created_at]]@@ -252,22 +252,22 @@(deftest settings-get-returns-live-models-test(mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider "anthropic/claude-haiku-4-5"llm.settings/llm-anthropic-api-key "sk-ant-valid"]- (with-redefs [metabot.self/list-models (fn- ([provider]- (is (= "anthropic" provider))- {:models [{:id "claude-haiku-4-5"- :display_name "Claude Haiku 4.5"}]})- ([provider {:keys [api-key]}]- (is (= "anthropic" provider))- (is (= "sk-ant-valid" api-key))- {:models [{:id "claude-sonnet-4-5"- :display_name "Claude Sonnet 4.5"}- {:id "claude-haiku-4-5"- :display_name "Claude Haiku 4.5"}- {:id "claude-opus-4-5"- :display_name "Claude Opus 4.5"}- {:id "claude-opus-4-1"- :display_name "Claude Opus 4.1"}]}))]+ (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn+ ([provider]+ (is (= "anthropic" provider))+ {:models [{:id "claude-haiku-4-5"+ :display_name "Claude Haiku 4.5"}]})+ ([provider {:keys [api-key]}]+ (is (= "anthropic" provider))+ (is (= "sk-ant-valid" api-key))+ {:models [{:id "claude-sonnet-4-5"+ :display_name "Claude Sonnet 4.5"}+ {:id "claude-haiku-4-5"+ :display_name "Claude Haiku 4.5"}+ {:id "claude-opus-4-5"+ :display_name "Claude Opus 4.5"}+ {:id "claude-opus-4-1"+ :display_name "Claude Opus 4.1"}]}))](is (= {:value "anthropic/claude-haiku-4-5":models [{:id "claude-haiku-4-5":display_name "Claude Haiku 4.5"@@ -285,12 +285,12 @@(deftest settings-get-normalizes-legacy-anthropic-ids-test(mt/with-temporary-setting-values [llm.settings/llm-anthropic-api-key "sk-ant-valid"]- (with-redefs [metabot.self/list-models (fn [_provider {:keys [api-key]}]- (is (= "sk-ant-valid" api-key))- {:models [{:id "claude-3-haiku-20240307"- :display_name "Claude 3 Haiku"}- {:id "claude-haiku-4-5"- :display_name "Claude Haiku 4.5"}]})]+ (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn [_provider {:keys [api-key]}]+ (is (= "sk-ant-valid" api-key))+ {:models [{:id "claude-3-haiku-20240307"+ :display_name "Claude 3 Haiku"}+ {:id "claude-haiku-4-5"+ :display_name "Claude Haiku 4.5"}]})](is (= {:value (metabot.settings/llm-metabot-provider):models [{:id "claude-3-haiku-20240307":display_name "Claude 3 Haiku"@@ -303,12 +303,12 @@(deftest settings-get-groups-openrouter-models-test(mt/with-temporary-setting-values [llm.settings/llm-openrouter-api-key "sk-or-v1-valid"]- (with-redefs [metabot.self/list-models (fn [_provider {:keys [api-key]}]- (is (= "sk-or-v1-valid" api-key))- {:models [{:id "openai/gpt-4.1-mini"- :display_name "OpenAI: GPT-4.1 mini"}- {:id "anthropic/claude-sonnet-4.5"- :display_name "Anthropic: Claude Sonnet 4.5"}]})]+ (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn [_provider {:keys [api-key]}]+ (is (= "sk-or-v1-valid" api-key))+ {:models [{:id "openai/gpt-4.1-mini"+ :display_name "OpenAI: GPT-4.1 mini"}+ {:id "anthropic/claude-sonnet-4.5"+ :display_name "Anthropic: Claude Sonnet 4.5"}]})](is (= {:value (metabot.settings/llm-metabot-provider):models [{:id "anthropic/claude-sonnet-4.5":display_name "Anthropic: Claude Sonnet 4.5"@@ -321,15 +321,15 @@(deftest settings-get-returns-metabase-models-without-api-key-test(mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider "metabase/anthropic/claude-sonnet-4-6"]- (with-redefs [metabot.self/list-models (fn- ([provider]- (is false (str "unexpected list-models call: " provider)))- ([provider opts]- (is (= "anthropic" provider))- (is (= {:ai-proxy? true} opts))- {:models [{:id "claude-haiku-4-5" :display_name "Claude Haiku 4.5"}- {:id "claude-sonnet-4-6" :display_name "Claude Sonnet 4.6"}- {:id "claude-opus-4-1" :display_name "Claude Opus 4.1"}]}))]+ (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn+ ([provider]+ (is false (str "unexpected list-models call: " provider)))+ ([provider opts]+ (is (= "anthropic" provider))+ (is (= {:ai-proxy? true} opts))+ {:models [{:id "claude-haiku-4-5" :display_name "Claude Haiku 4.5"}+ {:id "claude-sonnet-4-6" :display_name "Claude Sonnet 4.6"}+ {:id "claude-opus-4-1" :display_name "Claude Opus 4.1"}]}))](is (= {:value "metabase/anthropic/claude-sonnet-4-6":models [{:id "anthropic/claude-haiku-4-5" :display_name "Claude Haiku 4.5"}{:id "anthropic/claude-sonnet-4-6" :display_name "Claude Sonnet 4.6"}@@ -340,16 +340,16 @@(deftest settings-put-updates-provider-test(mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider "anthropic/claude-haiku-4-5"llm.settings/llm-openai-api-key "sk-valid"]- (with-redefs [metabot.self/list-models (fn- ([provider]- (is (= "openai" provider))- {:models [{:id "gpt-4.1-mini"- :display_name "GPT-4.1 mini"}]})- ([provider {:keys [api-key]}]- (is (= "openai" provider))- (is (= "sk-valid" api-key))- {:models [{:id "gpt-4.1-mini"- :display_name "GPT-4.1 mini"}]}))]+ (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn+ ([provider]+ (is (= "openai" provider))+ {:models [{:id "gpt-4.1-mini"+ :display_name "GPT-4.1 mini"}]})+ ([provider {:keys [api-key]}]+ (is (= "openai" provider))+ (is (= "sk-valid" api-key))+ {:models [{:id "gpt-4.1-mini"+ :display_name "GPT-4.1 mini"}]}))](is (= {:value "openai/gpt-4.1-mini":models [{:id "gpt-4.1-mini":display_name "GPT-4.1 mini"}]}@@ -361,15 +361,15 @@(deftest settings-put-updates-metabase-provider-without-api-key-test(mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider "anthropic/claude-haiku-4-5"]- (with-redefs [metabot.self/list-models (fn- ([provider]- (is false (str "unexpected list-models call: " provider)))- ([provider opts]- (is (= "anthropic" provider))- (is (= {:ai-proxy? true} opts))- {:models [{:id "claude-haiku-4-5" :display_name "Claude Haiku 4.5"}- {:id "claude-sonnet-4-6" :display_name "Claude Sonnet 4.6"}- {:id "claude-opus-4-1" :display_name "Claude Opus 4.1"}]}))]+ (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn+ ([provider]+ (is false (str "unexpected list-models call: " provider)))+ ([provider opts]+ (is (= "anthropic" provider))+ (is (= {:ai-proxy? true} opts))+ {:models [{:id "claude-haiku-4-5" :display_name "Claude Haiku 4.5"}+ {:id "claude-sonnet-4-6" :display_name "Claude Sonnet 4.6"}+ {:id "claude-opus-4-1" :display_name "Claude Opus 4.1"}]}))](is (= {:value "metabase/anthropic/claude-sonnet-4-6":models [{:id "anthropic/claude-haiku-4-5" :display_name "Claude Haiku 4.5"}{:id "anthropic/claude-sonnet-4-6" :display_name "Claude Sonnet 4.6"}@@ -382,15 +382,15 @@(deftest settings-put-defaults-empty-metabase-model-test(mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider "anthropic/claude-haiku-4-5"]- (with-redefs [metabot.self/list-models (fn- ([provider]- (is false (str "unexpected list-models call: " provider)))- ([provider opts]- (is (= "anthropic" provider))- (is (= {:ai-proxy? true} opts))- {:models [{:id "claude-haiku-4-5" :display_name "Claude Haiku 4.5"}- {:id "claude-sonnet-4-6" :display_name "Claude Sonnet 4.6"}- {:id "claude-opus-4-1" :display_name "Claude Opus 4.1"}]}))]+ (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn+ ([provider]+ (is false (str "unexpected list-models call: " provider)))+ ([provider opts]+ (is (= "anthropic" provider))+ (is (= {:ai-proxy? true} opts))+ {:models [{:id "claude-haiku-4-5" :display_name "Claude Haiku 4.5"}+ {:id "claude-sonnet-4-6" :display_name "Claude Sonnet 4.6"}+ {:id "claude-opus-4-1" :display_name "Claude Opus 4.1"}]}))](is (= {:value "metabase/anthropic/claude-sonnet-4-6":models [{:id "anthropic/claude-haiku-4-5" :display_name "Claude Haiku 4.5"}{:id "anthropic/claude-sonnet-4-6" :display_name "Claude Sonnet 4.6"}@@ -405,14 +405,14 @@(mt/with-temp-env-var-value! [mb-llm-anthropic-api-key nil](mt/with-temporary-setting-values [llm.settings/llm-anthropic-api-key nil](let [calls (atom 0)]- (with-redefs [metabot.self/list-models (fn [provider {:keys [api-key]}]- (swap! calls inc)- (is (= "anthropic" provider))- (is (= "sk-ant-valid" api-key))- (is (nil? (llm.settings/llm-anthropic-api-key))- "verification should happen before saving the key")- {:models [{:id "claude-haiku-4-5"- :display_name "Claude Haiku 4.5"}]})]+ (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn [provider {:keys [api-key]}]+ (swap! calls inc)+ (is (= "anthropic" provider))+ (is (= "sk-ant-valid" api-key))+ (is (nil? (llm.settings/llm-anthropic-api-key))+ "verification should happen before saving the key")+ {:models [{:id "claude-haiku-4-5"+ :display_name "Claude Haiku 4.5"}]})](is (= {:value (metabot.settings/llm-metabot-provider):models [{:id "claude-haiku-4-5":display_name "Claude Haiku 4.5"@@ -430,15 +430,15 @@(mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider "anthropic/claude-opus-4-1"llm.settings/llm-anthropic-api-key nil](let [calls (atom 0)]- (with-redefs [metabot.self/list-models (fn [provider {:keys [api-key]}]- (swap! calls inc)- (is (= "anthropic" provider))- (is (= "sk-ant-valid" api-key))- (is (nil? (llm.settings/llm-anthropic-api-key))- "verification should happen before saving the key")- {:models [{:id "claude-opus-4-1"- :display_name "Claude Opus 4.1"- :group "Opus"}]})]+ (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn [provider {:keys [api-key]}]+ (swap! calls inc)+ (is (= "anthropic" provider))+ (is (= "sk-ant-valid" api-key))+ (is (nil? (llm.settings/llm-anthropic-api-key))+ "verification should happen before saving the key")+ {:models [{:id "claude-opus-4-1"+ :display_name "Claude Opus 4.1"+ :group "Opus"}]})](is (= {:value "anthropic/claude-opus-4-1":models [{:id "claude-opus-4-1":display_name "Claude Opus 4.1"@@ -459,18 +459,18 @@(mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider "metabase/anthropic/claude-sonnet-4-6"llm.settings/llm-anthropic-api-key nil](let [calls (atom 0)]- (with-redefs [metabot.self/list-models (fn [provider {:keys [api-key]}]- (swap! calls inc)- (is (= "anthropic" provider))- (is (= "sk-ant-valid" api-key))- (is (nil? (llm.settings/llm-anthropic-api-key))- "verification should happen before saving the key")- {:models [{:id "claude-sonnet-4-6"- :display_name "Claude Sonnet 4.6"- :group "Sonnet"}- {:id "claude-opus-4-1"- :display_name "Claude Opus 4.1"- :group "Opus"}]})]+ (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn [provider {:keys [api-key]}]+ (swap! calls inc)+ (is (= "anthropic" provider))+ (is (= "sk-ant-valid" api-key))+ (is (nil? (llm.settings/llm-anthropic-api-key))+ "verification should happen before saving the key")+ {:models [{:id "claude-sonnet-4-6"+ :display_name "Claude Sonnet 4.6"+ :group "Sonnet"}+ {:id "claude-opus-4-1"+ :display_name "Claude Opus 4.1"+ :group "Opus"}]})](is (= {:value "anthropic/claude-sonnet-4-6":models [{:id "claude-opus-4-1":display_name "Claude Opus 4.1"@@ -492,13 +492,13 @@(deftest settings-put-blank-model-does-not-reset-when-provider-is-unchanged-test(mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider "anthropic/claude-opus-4-1"llm.settings/llm-anthropic-api-key "sk-ant-valid"]- (with-redefs [metabot.self/list-models (fn [provider {:keys [api-key]}]- (is (= "anthropic" provider))- (is (= "sk-ant-valid" api-key))- {:models [{:id "claude-sonnet-4-6"- :display_name "Claude Sonnet 4.6"}- {:id "claude-opus-4-1"- :display_name "Claude Opus 4.1"}]})]+ (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn [provider {:keys [api-key]}]+ (is (= "anthropic" provider))+ (is (= "sk-ant-valid" api-key))+ {:models [{:id "claude-sonnet-4-6"+ :display_name "Claude Sonnet 4.6"}+ {:id "claude-opus-4-1"+ :display_name "Claude Opus 4.1"}]})](is (= {:value "anthropic/claude-opus-4-1":models [{:id "claude-opus-4-1":display_name "Claude Opus 4.1"@@ -516,15 +516,15 @@(deftest settings-put-rejects-invalid-api-key-test(mt/with-temporary-setting-values [llm.settings/llm-openai-api-key nil](let [calls (atom 0)]- (with-redefs [metabot.self/list-models (fn [provider {:keys [api-key]}]- (swap! calls inc)- (is (= "openai" provider))- (is (= "sk-invalid" api-key))- (is (nil? (llm.settings/llm-openai-api-key))- "failed verification should not save the key")- (throw (ex-info "OpenAI API key expired or invalid"- {:api-error true- :status-code 401})))]+ (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn [provider {:keys [api-key]}]+ (swap! calls inc)+ (is (= "openai" provider))+ (is (= "sk-invalid" api-key))+ (is (nil? (llm.settings/llm-openai-api-key))+ "failed verification should not save the key")+ (throw (ex-info "OpenAI API key expired or invalid"+ {:api-error true+ :status-code 401})))](let [response (mt/user-http-request :crowberto :put 400 "metabot/settings"{:provider "openai":api-key "sk-invalid"})]@@ -535,12 +535,12 @@(deftest settings-put-does-not-treat-outages-as-invalid-keys-test(mt/with-temporary-setting-values [llm.settings/llm-openai-api-key nil]- (with-redefs [metabot.self/list-models (fn [provider {:keys [api-key]}]- (is (= "openai" provider))- (is (= "sk-valid" api-key))- (throw (ex-info "OpenAI API is not working but not saying why"- {:api-error true- :status-code 500})))]+ (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn [provider {:keys [api-key]}]+ (is (= "openai" provider))+ (is (= "sk-valid" api-key))+ (throw (ex-info "OpenAI API is not working but not saying why"+ {:api-error true+ :status-code 500})))](let [response (mt/user-http-request :crowberto :put 500 "metabot/settings"{:provider "openai":api-key "sk-valid"})]@@ -550,12 +550,12 @@(deftest settings-put-does-not-save-model-when-preflight-fails-test(mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider "anthropic/claude-haiku-4-5"llm.settings/llm-anthropic-api-key "sk-ant-valid"]- (with-redefs [metabot.self/list-models (fn [provider {:keys [api-key]}]- (is (= "anthropic" provider))- (is (= "sk-ant-valid" api-key))- (throw (ex-info "Anthropic API key has insufficient permissions"- {:api-error true- :status-code 403})))]+ (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn [provider {:keys [api-key]}]+ (is (= "anthropic" provider))+ (is (= "sk-ant-valid" api-key))+ (throw (ex-info "Anthropic API key has insufficient permissions"+ {:api-error true+ :status-code 403})))](let [response (mt/user-http-request :crowberto :put 400 "metabot/settings"{:provider "anthropic":model "claude-sonnet-4-5"})]@@ -565,10 +565,10 @@(deftest settings-get-surfaces-invalid-api-key-error-test(mt/with-temporary-setting-values [llm.settings/llm-openai-api-key "sk-invalid"]- (with-redefs [metabot.self/list-models (fn [_provider _opts]- (throw (ex-info "OpenAI API key expired or invalid"- {:api-error true- :status-code 401})))]+ (mt/with-dynamic-fn-redefs [metabot.self/list-models (fn [_provider _opts]+ (throw (ex-info "OpenAI API key expired or invalid"+ {:api-error true+ :status-code 401})))](is (= {:value (metabot.settings/llm-metabot-provider):api-key-error "OpenAI API key expired or invalid":models []}@@ -654,12 +654,12 @@:conversation_id (str (random-uuid)):history []:state {}}]- (with-redefs [openrouter/openrouter (fn [_]- (mut/mock-llm-response- [{:type :start :id "msg-1"}- {:type :text :text "Hello"}- {:type :usage :usage {:promptTokens 1 :completionTokens 1}- :model "test-model" :id "msg-1"}]))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter (fn [_]+ (mut/mock-llm-response+ [{:type :start :id "msg-1"}+ {:type :text :text "Hello"}+ {:type :usage :usage {:promptTokens 1 :completionTokens 1}+ :model "test-model" :id "msg-1"}]))](testing "Regular metabot is blocked when metabot-enabled is false"(mt/with-temporary-setting-values [metabot-enabled? false](mt/with-model-cleanup [:model/MetabotMessage@@ -966,15 +966,15 @@(testing "streaming-request passes metabot-id to native-agent-streaming-request"(let [captured-args (atom nil)test-metabot-id metabot.config/embedded-metabot-id]- (with-redefs [metabot.config/check-metabot-enabled! (constantly nil)- api/check-conversation-access! (constantly nil)- metabot.persistence/start-turn! (fn [& _]- {:assistant-msg-id 1- :assistant-external-id "ext-id"})- api/native-agent-streaming-request (fn [args]- (reset! captured-args args)- ;; Return a minimal streaming response- nil)]+ (mt/with-dynamic-fn-redefs [metabot.config/check-metabot-enabled! (constantly nil)+ api/check-conversation-access! (constantly nil)+ metabot.persistence/start-turn! (fn [& _]+ {:assistant-msg-id 1+ :assistant-external-id "ext-id"})+ api/native-agent-streaming-request (fn [args]+ (reset! captured-args args)+ ;; Return a minimal streaming response+ nil)](api/streaming-request {:metabot_id test-metabot-id:profile_id nil:message "test message"@@ -1005,8 +1005,8 @@ip-for (fn [conversation-id](:ip_address (t2/select-one :model/MetabotConversation :id conversation-id)))info-with-ip (fn [ip] {:origin nil :referer nil :user-agent nil :ip-address ip})]- (with-redefs [metabot.config/check-metabot-enabled! (constantly nil)- api/native-agent-streaming-request (constantly nil)]+ (mt/with-dynamic-fn-redefs [metabot.config/check-metabot-enabled! (constantly nil)+ api/native-agent-streaming-request (constantly nil)](mt/with-premium-features #{:audit-app}(mt/with-test-user :rasta(mt/with-temporary-setting-values [analytics-pii-retention-enabled true]@@ -1046,8 +1046,8 @@:ip-address nil})convo-for (fn [conversation-id](t2/select-one :model/MetabotConversation :id conversation-id))]- (with-redefs [metabot.config/check-metabot-enabled! (constantly nil)- api/native-agent-streaming-request (constantly nil)]+ (mt/with-dynamic-fn-redefs [metabot.config/check-metabot-enabled! (constantly nil)+ api/native-agent-streaming-request (constantly nil)](mt/with-premium-features #{:audit-app}(mt/with-test-user :rasta(mt/with-temporary-setting-values [analytics-pii-retention-enabled true]@@ -1087,12 +1087,12 @@(mt/with-premium-features #{:audit-app}(mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider test-provider](binding [scope/*current-user-metabot-permissions* scope/all-yes-permissions]- (with-redefs [openrouter/openrouter (fn [_]- (mut/mock-llm-response- [{:type :start :id "msg-1"}- {:type :text :text "hi"}- {:type :usage :usage {:promptTokens 1 :completionTokens 1}- :model "test-model" :id "msg-1"}]))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter (fn [_]+ (mut/mock-llm-response+ [{:type :start :id "msg-1"}+ {:type :text :text "hi"}+ {:type :usage :usage {:promptTokens 1 :completionTokens 1}+ :model "test-model" :id "msg-1"}]))](mt/with-model-cleanup [:model/MetabotMessage[:model/MetabotConversation :created_at]](testing "flag on: hostname AND path are recorded"@@ -1165,13 +1165,13 @@(deftest agent-streaming-returns-free-trial-limit-error-when-managed-provider-is-locked-test(mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider"metabase/anthropic/claude-sonnet-4-6"]- (with-redefs [premium-features/token-status (constantly {:meters {:anthropic:claude-sonnet-4-6:tokens {:meter-value 1000000- :is-locked true}}})- metabot.config/check-metabot-enabled! (constantly nil)- metabot.persistence/start-turn! (fn [& _]- (throw (ex-info "should not store messages" {})))- api/native-agent-streaming-request (fn [& _]- (throw (ex-info "should not call agent" {})))]+ (mt/with-dynamic-fn-redefs [premium-features/token-status (constantly {:meters {:anthropic:claude-sonnet-4-6:tokens {:meter-value 1000000+ :is-locked true}}})+ metabot.config/check-metabot-enabled! (constantly nil)+ metabot.persistence/start-turn! (fn [& _]+ (throw (ex-info "should not store messages" {})))+ api/native-agent-streaming-request (fn [& _]+ (throw (ex-info "should not call agent" {})))](mt/user-http-request :rasta :post 402 "metabot/agent-streaming"{:message "test message":context {}diff --git a/test/metabase/metabot/context_test.clj b/test/metabase/metabot/context_test.cljindex 3da1c76ab8c..7b8431ac1e8 100644--- a/test/metabase/metabot/context_test.clj+++ b/test/metabase/metabot/context_test.clj@@ -18,12 +18,12 @@(let [used [{:id 1 :name "used1"} {:id 2 :name "used2"}]extra [{:id 3 :name "extra1"} {:id 4 :name "extra2"}]all-tables (concat used extra)]- (with-redefs [table-utils/used-tables (fn [_] used)- table-utils/enhanced-database-tables (fn [_ {:keys [priority-tables all-tables-limit] :or {all-tables-limit 100}}]- (let [priority-ids (set (map :id priority-tables))- non-priority (remove #(priority-ids (:id %)) all-tables)- result (concat priority-tables (take (- all-tables-limit (count priority-tables)) non-priority))]- (take all-tables-limit result)))]+ (mt/with-dynamic-fn-redefs [table-utils/used-tables (fn [_] used)+ table-utils/enhanced-database-tables (fn [_ {:keys [priority-tables all-tables-limit] :or {all-tables-limit 100}}]+ (let [priority-ids (set (map :id priority-tables))+ non-priority (remove #(priority-ids (:id %)) all-tables)+ result (concat priority-tables (take (- all-tables-limit (count priority-tables)) non-priority))]+ (take all-tables-limit result)))](let [result (#'context/database-tables-for-context {:query users-native-query, :all-tables-limit 3})](is (= used result) "Should only return used tables, in order")(is (= (count used) (count result)) "Should return all used tables")@@ -35,12 +35,12 @@(let [used (mapv #(hash-map :id % :name (str "used" %)) (range 1 6)) ; 5 used tablesextra (mapv #(hash-map :id % :name (str "extra" %)) (range 6 10))all-tables (concat used extra)]- (with-redefs [table-utils/used-tables (fn [_] used)- table-utils/enhanced-database-tables (fn [_ {:keys [priority-tables all-tables-limit] :or {all-tables-limit 100}}]- (let [priority-ids (set (map :id priority-tables))- non-priority (remove #(priority-ids (:id %)) all-tables)- result (concat priority-tables (take (- all-tables-limit (count priority-tables)) non-priority))]- (take all-tables-limit result)))]+ (mt/with-dynamic-fn-redefs [table-utils/used-tables (fn [_] used)+ table-utils/enhanced-database-tables (fn [_ {:keys [priority-tables all-tables-limit] :or {all-tables-limit 100}}]+ (let [priority-ids (set (map :id priority-tables))+ non-priority (remove #(priority-ids (:id %)) all-tables)+ result (concat priority-tables (take (- all-tables-limit (count priority-tables)) non-priority))]+ (take all-tables-limit result)))](let [result (#'context/database-tables-for-context {:query users-native-query, :all-tables-limit 3})](is (= used result) "Should return all used tables")(is (= (count used) (count result)) "Should return all used tables")@@ -48,9 +48,9 @@(deftest database-tables-for-context-no-used-tables(let [extra (mapv #(hash-map :id % :name (str "extra" %)) (range 1 5))]- (with-redefs [table-utils/used-tables (fn [_] [])- table-utils/enhanced-database-tables (fn [_ opts]- (take (:all-tables-limit opts 100) extra))]+ (mt/with-dynamic-fn-redefs [table-utils/used-tables (fn [_] [])+ table-utils/enhanced-database-tables (fn [_ opts]+ (take (:all-tables-limit opts 100) extra))](let [result (#'context/database-tables-for-context {:query users-native-query, :all-tables-limit 3})](is (empty? result) "Should return empty when no used tables")))))@@ -58,12 +58,12 @@(let [used (mapv #(hash-map :id % :name (str "used" %)) (range 1 4)) ; 3 used tablesextra (mapv #(hash-map :id % :name (str "extra" %)) (range 4 7))all-tables (concat used extra)]- (with-redefs [table-utils/used-tables (fn [_] used)- table-utils/enhanced-database-tables (fn [_ {:keys [priority-tables all-tables-limit] :or {all-tables-limit 100}}]- (let [priority-ids (set (map :id priority-tables))- non-priority (remove #(priority-ids (:id %)) all-tables)- result (concat priority-tables (take (- all-tables-limit (count priority-tables)) non-priority))]- (take all-tables-limit result)))]+ (mt/with-dynamic-fn-redefs [table-utils/used-tables (fn [_] used)+ table-utils/enhanced-database-tables (fn [_ {:keys [priority-tables all-tables-limit] :or {all-tables-limit 100}}]+ (let [priority-ids (set (map :id priority-tables))+ non-priority (remove #(priority-ids (:id %)) all-tables)+ result (concat priority-tables (take (- all-tables-limit (count priority-tables)) non-priority))]+ (take all-tables-limit result)))](let [result (#'context/database-tables-for-context {:query users-native-query, :all-tables-limit 3})](is (= used result) "Should be exactly the used tables, in order")(is (= (count used) (count result)))@@ -71,16 +71,16 @@(deftest database-tables-for-context-exception-handling(testing "Returns empty when table-utils/enhanced-database-tables throws"- (with-redefs [table-utils/used-tables (fn [_] [{:id 1}])- table-utils/enhanced-database-tables (fn [_ _] (throw (Exception. "boom")))]+ (mt/with-dynamic-fn-redefs [table-utils/used-tables (fn [_] [{:id 1}])+ table-utils/enhanced-database-tables (fn [_ _] (throw (Exception. "boom")))](let [result (#'context/database-tables-for-context {:query users-native-query})](is (empty? result))))))(deftest database-tables-for-context-nil-used-tables(testing "Handles nil used-tables gracefully"- (with-redefs [table-utils/used-tables (fn [_] nil)- table-utils/enhanced-database-tables (fn [_ opts]- (take (:all-tables-limit opts 100) [{:id 1} {:id 2}]))]+ (mt/with-dynamic-fn-redefs [table-utils/used-tables (fn [_] nil)+ table-utils/enhanced-database-tables (fn [_ opts]+ (take (:all-tables-limit opts 100) [{:id 1} {:id 2}]))](let [result (#'context/database-tables-for-context {:query users-native-query})](is (empty? result) "Should return empty when used-tables is nil")))))@@ -88,8 +88,8 @@(testing "Deduplicates tables returned by database-tables"(let [used [{:id 1}]dup [{:id 1} {:id 1} {:id 2}]]- (with-redefs [table-utils/used-tables (fn [_] used)- table-utils/enhanced-database-tables (fn [_ _] dup)]+ (mt/with-dynamic-fn-redefs [table-utils/used-tables (fn [_] used)+ table-utils/enhanced-database-tables (fn [_ _] dup)](let [result (#'context/database-tables-for-context {:query users-native-query})](is (= [1 2] (map :id result)) "Should preserve order and remove duplicates"))))))@@ -97,7 +97,7 @@(deftest enhance-context-with-schema-native(let [mock-tables [{:id 1 :name "table1"} {:id 2 :name "table2"}]]- (with-redefs [context/database-tables-for-context (fn [_] mock-tables)]+ (mt/with-dynamic-fn-redefs [context/database-tables-for-context (fn [_] mock-tables)](testing "Enhances context with schema for native queries"(let [input {:user_is_viewing [{:query users-native-query}]}result (#'context/enhance-context-with-schema input)]@@ -118,7 +118,7 @@(deftest enhance-context-with-schema-complete-native-query(testing "Enhances context with schema for complete native query structure"(let [mock-tables [{:id 1 :name "users"} {:id 2 :name "orders"}]]- (with-redefs [context/database-tables-for-context (fn [_] mock-tables)]+ (mt/with-dynamic-fn-redefs [context/database-tables-for-context (fn [_] mock-tables)](let [input {:user_is_viewing [{:query users-native-query}]}result (#'context/enhance-context-with-schema input)](is (= (get-in result [:user_is_viewing 0 :used_tables]) mock-tables)))))))@@ -126,9 +126,9 @@(deftest enhance-context-with-schema-complete-mbql-query(testing "Does not enhance context for complete MBQL query structure and doesn't call database-tables-for-context"(let [call-count (atom 0)]- (with-redefs [context/database-tables-for-context (fn [_]- (swap! call-count inc)- [{:id 1 :name "should-not-be-used"}])]+ (mt/with-dynamic-fn-redefs [context/database-tables-for-context (fn [_]+ (swap! call-count inc)+ [{:id 1 :name "should-not-be-used"}])](let [input {:user_is_viewing [{:query users-mbql-query}]}result (#'context/enhance-context-with-schema input)](is (nil? (get-in result [:user_is_viewing 0 :used_tables]))@@ -140,8 +140,8 @@(testing "Enhances context with schema for Python transforms"(let [mock-tables [{:id 24 :name "orders" :schema "public"}{:id 31 :name "products" :schema "public"}]]- (with-redefs [context/python-transform-tables-for-context- (fn [_] mock-tables)]+ (mt/with-dynamic-fn-redefs [context/python-transform-tables-for-context+ (fn [_] mock-tables)](let [input {:user_is_viewing [{:type "transform":source {:type "python":source-database 2@@ -154,8 +154,8 @@(deftest enhance-context-with-schema-python-transform-no-source-tables(testing "Handles Python transform without source-tables"(let [called? (atom false)]- (with-redefs [context/python-transform-tables-for-context- (fn [_] (reset! called? true) nil)]+ (mt/with-dynamic-fn-redefs [context/python-transform-tables-for-context+ (fn [_] (reset! called? true) nil)](let [input {:user_is_viewing [{:type "transform":source {:type "python":source-database 2@@ -167,8 +167,8 @@(deftest enhance-context-with-schema-python-transform-no-source-database(testing "Handles Python transform without source-database"(let [called? (atom false)]- (with-redefs [context/python-transform-tables-for-context- (fn [_] (reset! called? true) nil)]+ (mt/with-dynamic-fn-redefs [context/python-transform-tables-for-context+ (fn [_] (reset! called? true) nil)](let [input {:user_is_viewing [{:type "transform":source {:type "python":source-tables [{:alias "orders" :table_id 24}]}}]}@@ -390,10 +390,10 @@(testing "Native query inside adhoc still uses SQL parsing path, not MBQL path"(let [called-mbql? (atom false)called-native? (atom false)]- (with-redefs [context/mbql-source-table-ids- (fn [_] (reset! called-mbql? true) nil)- context/database-tables-for-context- (fn [_] (reset! called-native? true) [{:id 1 :name "t"}])]+ (mt/with-dynamic-fn-redefs [context/mbql-source-table-ids+ (fn [_] (reset! called-mbql? true) nil)+ context/database-tables-for-context+ (fn [_] (reset! called-native? true) [{:id 1 :name "t"}])](let [input {:user_is_viewing [{:type "adhoc":query {:database (mt/id):type "native"diff --git a/test/metabase/metabot/example_question_generator_test.clj b/test/metabase/metabot/example_question_generator_test.cljindex 3c4d2b175cb..8d3af72f7dd 100644--- a/test/metabase/metabot/example_question_generator_test.clj+++ b/test/metabase/metabot/example_question_generator_test.clj@@ -59,7 +59,7 @@(deftest generate-example-questions-shape-test(testing "returns correct shape with mock LLM"(let [mock-response {:questions ["q1" "q2" "q3" "q4" "q5"]}]- (with-redefs [native-generator/call-llm (constantly mock-response)]+ (mt/with-dynamic-fn-redefs [native-generator/call-llm (constantly mock-response)](let [payload {:tables [{:name "Orders":description "Customer orders":fields [{:name "total" :type "number"}@@ -74,7 +74,7 @@(deftest generate-example-questions-empty-payload-test(testing "handles empty tables and metrics"- (with-redefs [native-generator/call-llm (fn [_] (throw (ex-info "should not be called" {})))]+ (mt/with-dynamic-fn-redefs [native-generator/call-llm (fn [_] (throw (ex-info "should not be called" {})))](is (=? {:table_questions []:metric_questions []}(native-generator/generate-example-questions {:tables [] :metrics []}))))))@@ -82,10 +82,10 @@(deftest generate-example-questions-parallel-test(testing "processes multiple items"(let [call-count (atom 0)]- (with-redefs [native-generator/call-llm- (fn [_]- (swap! call-count inc)- {:questions [(str "q" @call-count)]})]+ (mt/with-dynamic-fn-redefs [native-generator/call-llm+ (fn [_]+ (swap! call-count inc)+ {:questions [(str "q" @call-count)]})](let [payload {:tables [{:name "T1" :fields [{:name "a" :type "number"}]}{:name "T2" :fields [{:name "b" :type "string"}]}]:metrics [{:name "M1"@@ -99,7 +99,7 @@(deftest generate-example-questions-validation-failure-throws-test(testing "invalid LLM response propagates as exception"- (with-redefs [native-generator/call-llm (constantly {:bad "response"})]+ (mt/with-dynamic-fn-redefs [native-generator/call-llm (constantly {:bad "response"})](is (thrown-with-msg?Exception #"Invalid LLM response shape"(native-generator/generate-example-questions@@ -112,12 +112,12 @@;; self/call-llm-structured and parse-provider-model.(let [captured-opts (atom [])](mt/with-temporary-setting-values [llm-metabot-provider "openrouter/anthropic/claude-haiku-4-5"]- (with-redefs [openrouter/openrouter (fn [opts]- (swap! captured-opts conj opts)- [{:type :start :messageId "msg-1"}- {:type :tool-input-start :toolCallId "call-1" :toolName "json"}- {:type :tool-input-delta :toolCallId "call-1"- :inputTextDelta "{\"questions\":[\"q1\",\"q2\"]}"}])]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter (fn [opts]+ (swap! captured-opts conj opts)+ [{:type :start :messageId "msg-1"}+ {:type :tool-input-start :toolCallId "call-1" :toolName "json"}+ {:type :tool-input-delta :toolCallId "call-1"+ :inputTextDelta "{\"questions\":[\"q1\",\"q2\"]}"}])](testing "returns questions from openrouter responses"(is (=? {:table_questions [{:questions ["q1" "q2"]}]:metric_questions [{:questions ["q1" "q2"]}]}@@ -150,11 +150,11 @@(mt/with-temporary-setting-values [llm-metabot-provider "openrouter/test-model"](let [labels {:model "openrouter/test-model" :source "example-question-generation"}](testing "increments llm-requests and observes duration on success"- (with-redefs [openrouter/openrouter- (constantly (test-util/mock-llm-response- [{:type :start :id "m1"}- {:type :tool-input :id "call-1" :function "json"- :arguments {:questions ["q1"]}}]))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (constantly (test-util/mock-llm-response+ [{:type :start :id "m1"}+ {:type :tool-input :id "call-1" :function "json"+ :arguments {:questions ["q1"]}}]))](#'native-generator/call-llm "test prompt"))(is (== 1 (mt/metric-value system :metabase-metabot/llm-requests labels)))(is (pos? (:sum (mt/metric-value system :metabase-metabot/llm-duration-ms labels)))))))))@@ -165,13 +165,13 @@(testing "fires token_usage snowplow event for call-llm"(let [rasta-id (mt/user->id :rasta)](mt/with-temporary-setting-values [llm-metabot-provider "openrouter/test-model"]- (with-redefs [openrouter/openrouter- (constantly (test-util/mock-llm-response- [{:type :start :id "msg-1"}- {:type :tool-input :id "call-1" :function "json"- :arguments {:questions ["q1"]}}- {:type :usage :usage {:promptTokens 100 :completionTokens 20}- :model "test-model" :id "msg-1"}]))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (constantly (test-util/mock-llm-response+ [{:type :start :id "msg-1"}+ {:type :tool-input :id "call-1" :function "json"+ :arguments {:questions ["q1"]}}+ {:type :usage :usage {:promptTokens 100 :completionTokens 20}+ :model "test-model" :id "msg-1"}]))](mt/with-current-user rasta-id(snowplow-test/with-fake-snowplow-collector(#'native-generator/call-llm "test prompt")diff --git a/test/metabase/metabot/middleware/auth_test.clj b/test/metabase/metabot/middleware/auth_test.cljindex 6f3b933577a..816bce511c2 100644--- a/test/metabase/metabot/middleware/auth_test.clj+++ b/test/metabase/metabot/middleware/auth_test.clj@@ -41,7 +41,7 @@(assoc :body (java.io.ByteArrayInputStream. (.getBytes body "UTF-8")))))(deftest verify-slack-request-test- (with-redefs [mw.auth/current-unix-timestamp (constantly test-timestamp)]+ (mt/with-dynamic-fn-redefs [mw.auth/current-unix-timestamp (constantly test-timestamp)](testing "Valid signature w/ signing secret configured"(mt/with-temporary-raw-setting-values [metabot-slack-signing-secret test-signing-secret](let [body "test-body"@@ -83,7 +83,7 @@(deftest verify-slack-request-timestamp-validation-test(mt/with-temporary-raw-setting-values [metabot-slack-signing-secret test-signing-secret]- (with-redefs [mw.auth/current-unix-timestamp (constantly test-timestamp)]+ (mt/with-dynamic-fn-redefs [mw.auth/current-unix-timestamp (constantly test-timestamp)](testing "Replay attack prevention - rejects timestamps outside 5 minute window"(doseq [[expected offset-or-val description][[true 0 "current time"]diff --git a/test/metabase/metabot/self/claude_test.clj b/test/metabase/metabot/self/claude_test.cljindex 4d877d5f0f4..3683184b08c 100644--- a/test/metabase/metabot/self/claude_test.clj+++ b/test/metabase/metabot/self/claude_test.clj@@ -256,14 +256,14 @@:ai-proxy? true})))))(testing "Does not fall back to ai proxy when BYOK is missing"- (with-redefs [llm.settings/llm-anthropic-api-key (constantly nil)]+ (mt/with-dynamic-fn-redefs [llm.settings/llm-anthropic-api-key (constantly nil)](is (thrown-with-msg?clojure.lang.ExceptionInfo#"No Anthropic API key is set"(claude/claude-raw {:input [{:role :user :content "hi"}]})))))(testing "Throws an error if nothing is defined"- (with-redefs [llm.settings/llm-anthropic-api-key (constantly nil)]+ (mt/with-dynamic-fn-redefs [llm.settings/llm-anthropic-api-key (constantly nil)](mt/with-temporary-setting-values [llm.settings/llm-proxy-base-url nil](is (thrown-with-msg?clojure.lang.ExceptionInfo@@ -375,37 +375,37 @@(mt/with-temporary-setting-values [llm.settings/llm-anthropic-api-key "sk-ant-byok"llm.settings/llm-proxy-base-url "https://proxy.example"](testing "Prefers BYOK over ai proxy"- (with-redefs [http/request (fn [req]- (is (=? {:method :get- :url "https://api.anthropic.com/v1/models"- :headers {"anthropic-version" "2023-06-01"- "x-api-key" "sk-ant-byok"}}- req))- {:body "{\"data\":[]}"})]+ (mt/with-dynamic-fn-redefs [http/request (fn [req]+ (is (=? {:method :get+ :url "https://api.anthropic.com/v1/models"+ :headers {"anthropic-version" "2023-06-01"+ "x-api-key" "sk-ant-byok"}}+ req))+ {:body "{\"data\":[]}"})](is (= {:models []}(claude/list-models {})))))(testing "Uses ai proxy when explicitly requested"- (with-redefs [llm.settings/llm-anthropic-api-key (constantly nil)- http/request (fn [req]- (is (=? {:method :get- :url "https://proxy.example/anthropic/v1/models"- :headers {"anthropic-version" "2023-06-01"- "x-metabase-instance-token" "proxy-token"}}- req))- {:body "{\"data\":[]}"})]+ (mt/with-dynamic-fn-redefs [llm.settings/llm-anthropic-api-key (constantly nil)+ http/request (fn [req]+ (is (=? {:method :get+ :url "https://proxy.example/anthropic/v1/models"+ :headers {"anthropic-version" "2023-06-01"+ "x-metabase-instance-token" "proxy-token"}}+ req))+ {:body "{\"data\":[]}"})](is (= {:models []}(claude/list-models {:ai-proxy? true})))))(testing "Does not fall back to ai proxy when BYOK is missing"- (with-redefs [llm.settings/llm-anthropic-api-key (constantly nil)]+ (mt/with-dynamic-fn-redefs [llm.settings/llm-anthropic-api-key (constantly nil)](is (thrown-with-msg?clojure.lang.ExceptionInfo#"No Anthropic API key is set"(claude/list-models {})))))(testing "Throws an error if nothing is defined"- (with-redefs [llm.settings/llm-anthropic-api-key (constantly nil)]+ (mt/with-dynamic-fn-redefs [llm.settings/llm-anthropic-api-key (constantly nil)](mt/with-temporary-setting-values [llm.settings/llm-proxy-base-url nil](is (thrown-with-msg?clojure.lang.ExceptionInfodiff --git a/test/metabase/metabot/self/openai_test.clj b/test/metabase/metabot/self/openai_test.cljindex cd9b1233737..c9cbed7eef2 100644--- a/test/metabase/metabot/self/openai_test.clj+++ b/test/metabase/metabot/self/openai_test.clj@@ -167,7 +167,7 @@(deftest openai-auth-preferences-test(mt/with-premium-features #{:metabase-ai-managed}- (with-redefs [premium-features/premium-embedding-token (constantly "proxy-token")]+ (mt/with-dynamic-fn-redefs [premium-features/premium-embedding-token (constantly "proxy-token")](mt/with-temporary-setting-values [llm.settings/llm-openai-api-key "sk-ant-byok"llm.settings/llm-proxy-base-url "https://proxy.example"](testing "Prefers BYOK over ai proxy"diff --git a/test/metabase/metabot/self/openrouter_test.clj b/test/metabase/metabot/self/openrouter_test.cljindex 59b16e0dbdc..60311ec707f 100644--- a/test/metabase/metabot/self/openrouter_test.clj+++ b/test/metabase/metabot/self/openrouter_test.clj@@ -187,7 +187,7 @@(deftest openrouter-auth-preferences-test(mt/with-premium-features #{:metabase-ai-managed}- (with-redefs [premium-features/premium-embedding-token (constantly "proxy-token")]+ (mt/with-dynamic-fn-redefs [premium-features/premium-embedding-token (constantly "proxy-token")](mt/with-temporary-setting-values [llm.settings/llm-openrouter-api-key "sk-or-v1-byok"llm.settings/llm-proxy-base-url "https://proxy.example"](testing "Prefers BYOK over ai proxy"diff --git a/test/metabase/metabot/self/schema_test.clj b/test/metabase/metabot/self/schema_test.cljindex 2d62807bd94..46bc038cd3c 100644--- a/test/metabase/metabot/self/schema_test.clj+++ b/test/metabase/metabot/self/schema_test.clj@@ -3,7 +3,8 @@[clojure.test :refer :all][malli.core :as mc][metabase.metabot.self.features :as features]- [metabase.metabot.self.schema :as schema]))+ [metabase.metabot.self.schema :as schema]+ [metabase.test :as mt]))(set! *warn-on-reflection* true)@@ -13,7 +14,7 @@(deftest ^:synchronized filter-schema-by-features-available-feature-test(testing "entry with available feature is kept, :feature prop stripped"- (with-redefs [features/feature-available? (constantly true)]+ (mt/with-dynamic-fn-redefs [features/feature-available? (constantly true)](let [input [:map [:field {:feature :some-feature} :string]]result (schema/filter-schema-by-features input)children (mc/children result)]@@ -23,7 +24,7 @@(deftest ^:synchronized filter-schema-by-features-unavailable-feature-test(testing "entry with unavailable feature is removed"- (with-redefs [features/feature-available? (constantly false)]+ (mt/with-dynamic-fn-redefs [features/feature-available? (constantly false)](let [input [:map [:field {:feature :some-feature} :string]]result (schema/filter-schema-by-features input)children (mc/children result)]@@ -31,7 +32,7 @@(deftest ^:synchronized filter-schema-by-features-no-feature-annotation-test(testing "entry without :feature annotation passes through unchanged"- (with-redefs [features/feature-available? (fn [_] (throw (ex-info "should not be called" {})))]+ (mt/with-dynamic-fn-redefs [features/feature-available? (fn [_] (throw (ex-info "should not be called" {})))](let [input [:map [:field :string]]result (schema/filter-schema-by-features input)children (mc/children result)]@@ -41,7 +42,7 @@(deftest ^:synchronized filter-schema-by-features-mixed-entries-test(testing "map with mixed entries: only unavailable feature-gated entries removed"- (with-redefs [features/feature-available? #(= :available-feature %)]+ (mt/with-dynamic-fn-redefs [features/feature-available? #(= :available-feature %)](let [input [:map[:always-present :string][:gated-available {:feature :available-feature} :int]@@ -56,7 +57,7 @@(deftest ^:synchronized filter-schema-by-features-nested-maps-test(testing "nested map schemas are also filtered"- (with-redefs [features/feature-available? (constantly false)]+ (mt/with-dynamic-fn-redefs [features/feature-available? (constantly false)](let [input [:map[:outer :string][:nested [:map@@ -73,7 +74,7 @@(deftest ^:synchronized filter-schema-by-features-non-map-schema-test(testing "non-map schemas pass through unchanged"- (with-redefs [features/feature-available? (constantly false)]+ (mt/with-dynamic-fn-redefs [features/feature-available? (constantly false)](let [sequential-schema [:sequential :string]string-schema :stringenum-schema [:enum "a" "b"]]@@ -83,7 +84,7 @@(deftest ^:synchronized filter-schema-by-features-optional-and-feature-test(testing "entry with both :optional and :feature handles both properties"- (with-redefs [features/feature-available? (constantly true)]+ (mt/with-dynamic-fn-redefs [features/feature-available? (constantly true)](let [input [:map [:field {:optional true :feature :some-feature} :string]]result (schema/filter-schema-by-features input)children (mc/children result)@@ -95,7 +96,7 @@(deftest ^:synchronized filter-schema-by-features-all-entries-filtered-test(testing "all feature-gated entries unavailable results in empty map"- (with-redefs [features/feature-available? (constantly false)]+ (mt/with-dynamic-fn-redefs [features/feature-available? (constantly false)](let [input [:map {:closed true}[:field1 {:feature :f1} :string][:field2 {:feature :f2} :int]]@@ -107,7 +108,7 @@(deftest ^:synchronized filter-schema-by-features-preserves-map-properties-test(testing "map-level properties like :closed are preserved"- (with-redefs [features/feature-available? (constantly true)]+ (mt/with-dynamic-fn-redefs [features/feature-available? (constantly true)](let [input [:map {:closed true} [:field :string]]result (schema/filter-schema-by-features input)props (mc/properties result)]@@ -115,7 +116,7 @@(deftest ^:synchronized filter-schema-by-features-complex-nested-structure-test(testing "complex nesting with sequential containing map"- (with-redefs [features/feature-available? #(= :enabled %)]+ (mt/with-dynamic-fn-redefs [features/feature-available? #(= :enabled %)](let [input [:map[:items [:sequential[:mapdiff --git a/test/metabase/metabot/self_test.clj b/test/metabase/metabot/self_test.cljindex 8fe1e79ea65..e7170833110 100644--- a/test/metabase/metabot/self_test.clj+++ b/test/metabase/metabot/self_test.clj@@ -552,7 +552,7 @@500 1 (ex-info "err" {:status 429 :headers {"retry-after" "120"}}))))(deftest with-retries-test- (with-redefs [self/retry-delay-ms (constantly 0)]+ (mt/with-dynamic-fn-redefs [self/retry-delay-ms (constantly 0)](testing "succeeds on first attempt without retrying"(let [calls (atom 0)](is (= :ok (#'self/with-retries@@ -605,10 +605,10 @@(deftest call-llm-prometheus-test(mt/with-prometheus-system! [_ system]- (with-redefs [self/retry-delay-ms (constantly 0)]+ (mt/with-dynamic-fn-redefs [self/retry-delay-ms (constantly 0)](let [labels {:model "openrouter/test-model" :source "metabot_agent"}](testing "increments llm-requests and observes duration on success"- (with-redefs [openrouter/openrouter (constantly (test-util/mock-llm-response [{:type :start :id "m1"}]))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter (constantly (test-util/mock-llm-response [{:type :start :id "m1"}]))](run! identity (self/call-llm "openrouter/test-model" nil [] {} {:tag "metabot_agent"})))(is (== 1 (mt/metric-value system :metabase-metabot/llm-requests labels)))(is (== 0 (mt/metric-value system :metabase-metabot/llm-retries labels)))@@ -623,13 +623,13 @@(testing "increments llm-retries on transient failures, no errors on eventual success"(let [calls (atom 0)](mt/with-log-level [metabase.metabot.self :fatal]- (with-redefs [openrouter/openrouter- (fn [_opts]- (reify clojure.lang.IReduceInit- (reduce [_ rf init]- (if (< (swap! calls inc) 3)- (throw (ex-info "rate limited" {:status 429}))- (reduce rf init (test-util/mock-llm-response [{:type :start :id "m1"}]))))))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (fn [_opts]+ (reify clojure.lang.IReduceInit+ (reduce [_ rf init]+ (if (< (swap! calls inc) 3)+ (throw (ex-info "rate limited" {:status 429}))+ (reduce rf init (test-util/mock-llm-response [{:type :start :id "m1"}]))))))](run! identity (self/call-llm "openrouter/test-model" nil [] {} {:tag "metabot_agent"}))))(is (== 3 (mt/metric-value system :metabase-metabot/llm-requests labels)))(is (== 2 (mt/metric-value system :metabase-metabot/llm-retries labels)))@@ -642,11 +642,11 @@(analytics/clear! :metabase-metabot/llm-duration-ms)(testing "increments llm-errors on non-retryable failure, no retries"- (with-redefs [openrouter/openrouter- (fn [_opts]- (reify clojure.lang.IReduceInit- (reduce [_ _rf _init]- (throw (ex-info "unauthorized" {:status 401})))))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (fn [_opts]+ (reify clojure.lang.IReduceInit+ (reduce [_ _rf _init]+ (throw (ex-info "unauthorized" {:status 401})))))](is (thrown? Exception (run! identity (self/call-llm "openrouter/test-model" nil [] {} {:tag "metabot_agent"})))))(is (== 1 (mt/metric-value system :metabase-metabot/llm-requests labels)))(is (== 0 (mt/metric-value system :metabase-metabot/llm-retries labels)))@@ -659,21 +659,21 @@(analytics/clear! :metabase-metabot/llm-duration-ms)(testing "increments llm-errors with :error-type llm-sse-error on inline SSE errors"- (with-redefs [openrouter/openrouter- (constantly (test-util/mock-llm-response [{:type :error :errorText "content policy violation"}]))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (constantly (test-util/mock-llm-response [{:type :error :errorText "content policy violation"}]))](run! identity (self/call-llm "openrouter/test-model" nil [] {} {:tag "metabot_agent"})))(is (== 1 (mt/metric-value system :metabase-metabot/llm-requests labels)))(is (== 1 (mt/metric-value system :metabase-metabot/llm-errors(assoc labels :error-type "llm-sse-error")))))(testing "reports token usage metrics on :usage parts"- (with-redefs [openrouter/openrouter- (constantly (test-util/mock-llm-response- [{:type :start- :id "m1"}- {:type :usage- :usage {:promptTokens 100 :completionTokens 25}- :model "test-model"}]))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (constantly (test-util/mock-llm-response+ [{:type :start+ :id "m1"}+ {:type :usage+ :usage {:promptTokens 100 :completionTokens 25}+ :model "test-model"}]))](run! identity (self/call-llm "openrouter/test-model" nil [] {} {:tag "metabot_agent"})))(is (== 100 (mt/metric-value system :metabase-metabot/llm-input-tokens labels)))(is (== 25 (mt/metric-value system :metabase-metabot/llm-output-tokens labels)))@@ -686,15 +686,15 @@(testing "increments cache token counters when the :usage part carries cache fields";; :promptTokens is the pre-summed total input (40 fresh + 300 cache_creation + 1200 cache_read = 1540).- (with-redefs [openrouter/openrouter- (constantly (test-util/mock-llm-response- [{:type :start :id "m1"}- {:type :usage- :usage {:promptTokens 1540- :completionTokens 10- :cacheCreationTokens 300- :cacheReadTokens 1200}- :model "test-model"}]))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (constantly (test-util/mock-llm-response+ [{:type :start :id "m1"}+ {:type :usage+ :usage {:promptTokens 1540+ :completionTokens 10+ :cacheCreationTokens 300+ :cacheReadTokens 1200}+ :model "test-model"}]))](run! identity (self/call-llm "openrouter/test-model" nil [] {} {:tag "metabot_agent"})))(is (== 300 (mt/metric-value system :metabase-metabot/llm-cache-creation-tokens labels)))(is (== 1200 (mt/metric-value system :metabase-metabot/llm-cache-read-tokens labels))))@@ -705,19 +705,19 @@(analytics/clear! :metabase-metabot/llm-cache-read-tokens)(testing "does not increment cache counters when cache fields are absent or zero"- (with-redefs [openrouter/openrouter- (constantly (test-util/mock-llm-response- [{:type :start :id "m1"}- {:type :usage- :usage {:promptTokens 10 :completionTokens 5}- :model "test-model"}]))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (constantly (test-util/mock-llm-response+ [{:type :start :id "m1"}+ {:type :usage+ :usage {:promptTokens 10 :completionTokens 5}+ :model "test-model"}]))](run! identity (self/call-llm "openrouter/test-model" nil [] {} {:tag "metabot_agent"})))(is (zero? (mt/metric-value system :metabase-metabot/llm-cache-creation-tokens labels)))(is (zero? (mt/metric-value system :metabase-metabot/llm-cache-read-tokens labels))))))))(deftest call-llm-structured-prometheus-test(mt/with-prometheus-system! [_ system]- (with-redefs [self/retry-delay-ms (constantly 0)]+ (mt/with-dynamic-fn-redefs [self/retry-delay-ms (constantly 0)](let [labels {:model "openrouter/test-model" :source "metabot_agent"}success-mock (test-util/mock-llm-response[{:type :start :id "m1"}@@ -729,7 +729,7 @@{:type "object" :properties {:answer {:type "string"}}}0.3 1024 {:tag "metabot_agent"})](testing "increments llm-requests and observes duration on success"- (with-redefs [openrouter/openrouter (constantly success-mock)]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter (constantly success-mock)](call-structured!))(is (== 1 (mt/metric-value system :metabase-metabot/llm-requests labels)))(is (== 0 (mt/metric-value system :metabase-metabot/llm-retries labels)))@@ -743,11 +743,11 @@(testing "increments llm-retries on transient failures, no errors on eventual success"(let [calls (atom 0)](mt/with-log-level [metabase.metabot.self :fatal]- (with-redefs [openrouter/openrouter- (fn [_opts]- (if (< (swap! calls inc) 3)- (throw (ex-info "rate limited" {:status 429}))- success-mock))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (fn [_opts]+ (if (< (swap! calls inc) 3)+ (throw (ex-info "rate limited" {:status 429}))+ success-mock))](call-structured!))))(is (== 3 (mt/metric-value system :metabase-metabot/llm-requests labels)))(is (== 2 (mt/metric-value system :metabase-metabot/llm-retries labels)))@@ -760,8 +760,8 @@(analytics/clear! :metabase-metabot/llm-duration-ms)(testing "increments llm-errors on non-retryable failure, no retries"- (with-redefs [openrouter/openrouter- (fn [_opts] (throw (ex-info "unauthorized" {:status 401})))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (fn [_opts] (throw (ex-info "unauthorized" {:status 401})))](is (thrown? Exception (call-structured!))))(is (== 1 (mt/metric-value system :metabase-metabot/llm-requests labels)))(is (== 0 (mt/metric-value system :metabase-metabot/llm-retries labels)))@@ -774,22 +774,22 @@(analytics/clear! :metabase-metabot/llm-duration-ms)(testing "increments llm-errors with :error-type llm-sse-error on inline SSE errors"- (with-redefs [openrouter/openrouter- (constantly (test-util/mock-llm-response- [{:type :error :errorText "content policy violation"}]))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (constantly (test-util/mock-llm-response+ [{:type :error :errorText "content policy violation"}]))](is (thrown? Exception (call-structured!))))(is (== 1 (mt/metric-value system :metabase-metabot/llm-requests labels)))(is (== 1 (mt/metric-value system :metabase-metabot/llm-errors(assoc labels :error-type "llm-sse-error")))))(testing "reports token usage metrics on :usage parts"- (with-redefs [openrouter/openrouter- (constantly (test-util/mock-llm-response- [{:type :start :id "m1"}- {:type :tool-input :id "call-1" :function "json"- :arguments {:answer "42"}}- {:type :usage :usage {:promptTokens 100 :completionTokens 25}- :model "test-model"}]))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (constantly (test-util/mock-llm-response+ [{:type :start :id "m1"}+ {:type :tool-input :id "call-1" :function "json"+ :arguments {:answer "42"}}+ {:type :usage :usage {:promptTokens 100 :completionTokens 25}+ :model "test-model"}]))](call-structured!))(is (== 100 (mt/metric-value system :metabase-metabot/llm-input-tokens labels)))(is (== 25 (mt/metric-value system :metabase-metabot/llm-output-tokens labels)))@@ -809,16 +809,16 @@;; The adapter pre-sums input + cache_creation + cache_read into :promptTokens,;; so the mock supplies the already-summed value (950 = 100 fresh + 50 cache_creation + 800 cache_read).;; total_tokens reverts to prompt + completion = 950 + 20 = 970.- (with-redefs [openrouter/openrouter- (constantly (test-util/mock-llm-response- [{:type :start :id "msg-1"}- {:type :tool-input :id "call-1" :function "get-time"- :arguments {:tz "UTC"}}- {:type :usage :usage {:promptTokens 950- :completionTokens 20- :cacheCreationTokens 50- :cacheReadTokens 800}- :model "test-model" :id "msg-1"}]))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (constantly (test-util/mock-llm-response+ [{:type :start :id "msg-1"}+ {:type :tool-input :id "call-1" :function "get-time"+ :arguments {:tz "UTC"}}+ {:type :usage :usage {:promptTokens 950+ :completionTokens 20+ :cacheCreationTokens 50+ :cacheReadTokens 800}+ :model "test-model" :id "msg-1"}]))](mt/with-current-user rasta-id(snowplow-test/with-fake-snowplow-collector(run! identity (self/call-llm "openrouter/test-model" nil [] test-util/TOOLS snowplow-tracking-opts))@@ -850,13 +850,13 @@(deftest call-llm-structured-snowplow-test(testing "fires :snowplow/token_usage event for call-llm-structured"(let [rasta-id (mt/user->id :rasta)]- (with-redefs [openrouter/openrouter- (constantly (test-util/mock-llm-response- [{:type :start :id "msg-1"}- {:type :tool-input :id "call-1" :function "json"- :arguments {:answer "42"}}- {:type :usage :usage {:promptTokens 50 :completionTokens 10}- :model "test-model" :id "msg-1"}]))]+ (mt/with-dynamic-fn-redefs [openrouter/openrouter+ (constantly (test-util/mock-llm-response+ [{:type :start :id "msg-1"}+ {:type :tool-input :id "call-1" :function "json"+ :arguments {:answer "42"}}+ {:type :usage :usage {:promptTokens 50 :completionTokens 10}+ :model "test-model" :id "msg-1"}]))](mt/with-current-user rasta-id(snowplow-test/with-fake-snowplow-collector(self/call-llm-structured "openrouter/test-model"diff --git a/test/metabase/metabot/settings_test.clj b/test/metabase/metabot/settings_test.cljindex 1332c5e8b7d..1bfea714311 100644--- a/test/metabase/metabot/settings_test.clj+++ b/test/metabase/metabot/settings_test.clj@@ -98,14 +98,14 @@(deftest metabot-configured-with-direct-provider-no-api-key-test(testing "returns false when direct provider has no API key"- (with-redefs [llm.settings/llm-anthropic-api-key (constantly nil)]+ (mt/with-dynamic-fn-redefs [llm.settings/llm-anthropic-api-key (constantly nil)](mt/with-temporary-setting-values [llm-metabot-provider "anthropic/claude-sonnet-4-6"](is (false? (metabot.settings/llm-metabot-configured?)))))))(deftest metabot-configured-proxy-url-not-fallback-for-direct-provider-test(testing "proxy URL alone does not make a direct provider configured"(mt/with-premium-features #{:metabase-ai-managed}- (with-redefs [llm.settings/llm-anthropic-api-key (constantly nil)]+ (mt/with-dynamic-fn-redefs [llm.settings/llm-anthropic-api-key (constantly nil)](mt/with-temporary-setting-values [llm-metabot-provider "anthropic/claude-sonnet-4-6"llm-proxy-base-url "https://proxy.example.com"](is (false? (metabot.settings/llm-metabot-configured?))))))))diff --git a/test/metabase/metabot/table_utils_test.clj b/test/metabase/metabot/table_utils_test.cljindex 659f081448c..aab95a78f31 100644--- a/test/metabase/metabot/table_utils_test.clj+++ b/test/metabase/metabot/table_utils_test.clj@@ -170,9 +170,9 @@(testing "handles query with recognized tables"(mt/with-current-user (mt/user->id :crowberto);; Mock query analyzer result with recognized table- (with-redefs [query-analyzer/tables-for-native- (fn [_query & _opts]- {:tables [{:table "users" :table-id table1-id :schema "public"}]})]+ (mt/with-dynamic-fn-redefs [query-analyzer/tables-for-native+ (fn [_query & _opts]+ {:tables [{:table "users" :table-id table1-id :schema "public"}]})](let [query (mt/with-db db(lib/native-query (mt/metadata-provider) "SELECT * FROM users"))tables (table-utils/used-tables query)]@@ -182,9 +182,9 @@(testing "handles query with unrecognized tables that have fuzzy matches"(mt/with-current-user (mt/user->id :crowberto);; Mock query analyzer result with unrecognized table- (with-redefs [query-analyzer/tables-for-native- (fn [_query & _opts]- {:tables [{:table "user" :schema "public"}]})] ; "user" should match "users"+ (mt/with-dynamic-fn-redefs [query-analyzer/tables-for-native+ (fn [_query & _opts]+ {:tables [{:table "user" :schema "public"}]})] ; "user" should match "users"(let [query (mt/with-db db(lib/native-query (mt/metadata-provider) "SELECT * FROM user"))tables (table-utils/used-tables query)]@@ -194,8 +194,8 @@(testing "handles empty query analysis result"(mt/with-current-user (mt/user->id :crowberto)- (with-redefs [query-analyzer/tables-for-native- (fn [_query & _opts] {:tables []})]+ (mt/with-dynamic-fn-redefs [query-analyzer/tables-for-native+ (fn [_query & _opts] {:tables []})](let [query (mt/with-db db(lib/native-query (mt/metadata-provider) "SELECT 1"))tables (table-utils/used-tables query)]@@ -203,10 +203,10 @@(testing "handles mixed recognized and unrecognized tables"(mt/with-current-user (mt/user->id :crowberto)- (with-redefs [query-analyzer/tables-for-native- (fn [_query & _opts]- {:tables [{:table "users" :table-id table1-id :schema "public"} ; recognized- {:table "order" :schema "public"}]})] ; unrecognized, should match "orders"+ (mt/with-dynamic-fn-redefs [query-analyzer/tables-for-native+ (fn [_query & _opts]+ {:tables [{:table "users" :table-id table1-id :schema "public"} ; recognized+ {:table "order" :schema "public"}]})] ; unrecognized, should match "orders"(let [query (mt/with-db db(lib/native-query (mt/metadata-provider) "SELECT * FROM users JOIN order ON ..."))tables (table-utils/used-tables query)]@@ -302,8 +302,8 @@(is (empty? matches))))))(testing "used-tables handles query analyzer exceptions"- (with-redefs [query-analyzer/tables-for-native- (fn [_query & _opts] (throw (Exception. "Query analysis failed")))]+ (mt/with-dynamic-fn-redefs [query-analyzer/tables-for-native+ (fn [_query & _opts] (throw (Exception. "Query analysis failed")))](let [query (lib/native-query (mt/metadata-provider) "SELECT * FROM users")](is (thrown? Exception (table-utils/used-tables query))))))@@ -433,9 +433,9 @@:model/Field {} {:table_id table4-id, :name "id", :database_type "INTEGER"}](mt/with-current-user (mt/user->id :crowberto);; Mock query analyzer to return only "users" table- (with-redefs [query-analyzer/tables-for-native- (fn [_query & _opts]- {:tables [{:table "users" :table-id table1-id :schema "public"}]})]+ (mt/with-dynamic-fn-redefs [query-analyzer/tables-for-native+ (fn [_query & _opts]+ {:tables [{:table "users" :table-id table1-id :schema "public"}]})](let [query (mt/with-db db(lib/native-query (mt/metadata-provider) "SELECT * FROM users"));; Set limit to 2, but we have 4 tables, so it should use query-based selection@@ -522,10 +522,10 @@:model/Field {} {:table_id table3-id, :name "id", :database_type "INTEGER"}:model/Field {} {:table_id table4-id, :name "id", :database_type "INTEGER"}](mt/with-current-user (mt/user->id :crowberto)- (with-redefs [query-analyzer/tables-for-native- (fn [_query & _opts]- {:tables [{:table "users" :table-id table1-id :schema "public"}- {:table "products" :table-id table3-id :schema "public"}]})]+ (mt/with-dynamic-fn-redefs [query-analyzer/tables-for-native+ (fn [_query & _opts]+ {:tables [{:table "users" :table-id table1-id :schema "public"}+ {:table "products" :table-id table3-id :schema "public"}]})](let [query (mt/with-db db(lib/native-query (mt/metadata-provider) "SELECT * FROM users JOIN products"))ddl (table-utils/schema-sample query {:all-tables-limit 1})]@@ -545,10 +545,10 @@:model/Field {} {:table_id table2-id, :name "id", :database_type "INTEGER"}:model/Field {} {:table_id table3-id, :name "id", :database_type "INTEGER"}](mt/with-current-user (mt/user->id :crowberto)- (with-redefs [query-analyzer/tables-for-native- (fn [_query & _opts]+ (mt/with-dynamic-fn-redefs [query-analyzer/tables-for-native+ (fn [_query & _opts];; Return "order" which will fuzzy match multiple tables- {:tables [{:table "order" :schema "public"}]})]+ {:tables [{:table "order" :schema "public"}]})](let [query (mt/with-db db(lib/native-query (mt/metadata-provider) "SELECT * FROM order"))ddl (table-utils/schema-sample query {:all-tables-limit 1})]diff --git a/test/metabase/metabot/task/suggested_prompts_generator_test.clj b/test/metabase/metabot/task/suggested_prompts_generator_test.cljindex ccf457e1e34..7b6ae8b79cf 100644--- a/test/metabase/metabot/task/suggested_prompts_generator_test.clj+++ b/test/metabase/metabot/task/suggested_prompts_generator_test.clj@@ -28,16 +28,16 @@{card-id :id}{:type :model:dataset_query query}]- (with-redefs [metabot.example-question-generator/generate-example-questions- (fn [input]+ (mt/with-dynamic-fn-redefs [metabot.example-question-generator/generate-example-questions+ (fn [input];; Return fake prompts if we have cards, empty otherwise- (if (or (seq (:metrics input)) (seq (:tables input)))- {:table_questions [{:questions ["What is the total for this model?"- "How many items are in this model?"]}]- :metric_questions [{:questions ["What is the current value of this metric?"- "How has this metric changed over time?"]}]}- {:table_questions []- :metric_questions []}))]+ (if (or (seq (:metrics input)) (seq (:tables input)))+ {:table_questions [{:questions ["What is the total for this model?"+ "How many items are in this model?"]}]+ :metric_questions [{:questions ["What is the current value of this metric?"+ "How has this metric changed over time?"]}]}+ {:table_questions []+ :metric_questions []}))](testing "Non-verified card with use_verified_content=false generates prompts"(t2/update! :model/Metabot (:id original-metabot) {:use_verified_content false})@@ -96,11 +96,11 @@{:type :model:dataset_query query}](t2/update! :model/Metabot (:id original-metabot) {:use_verified_content false})- (with-redefs [premium-features/token-status- (constantly {:meters {:anthropic:claude-sonnet-4-6:tokens {:meter-value 1000000- :is-locked true}}})- metabot.example-question-generator/generate-example-questions- (fn [& _]- (throw (ex-info "should not generate prompts" {})))]+ (mt/with-dynamic-fn-redefs [premium-features/token-status+ (constantly {:meters {:anthropic:claude-sonnet-4-6:tokens {:meter-value 1000000+ :is-locked true}}})+ metabot.example-question-generator/generate-example-questions+ (fn [& _]+ (throw (ex-info "should not generate prompts" {})))](#'metabot.task.suggested-prompts-generator/maybe-generate-suggested-prompts!)(is (empty? (t2/select :model/MetabotPrompt :card_id card-id)))))))))))diff --git a/test/metabase/metabot/tools/create_alert_test.clj b/test/metabase/metabot/tools/create_alert_test.cljindex 03fa37b71c1..93c5862b418 100644--- a/test/metabase/metabot/tools/create_alert_test.clj+++ b/test/metabase/metabot/tools/create_alert_test.clj@@ -22,8 +22,8 @@(let [invoke-tool #(mt/with-current-user (mt/user->id :rasta)(metabot.tools.create-alert/create-alert %))base-data (alert-data card-id)]- (with-redefs [channel.settings/slack-configured? (constantly true)- channel.settings/slack-cached-channels-and-usernames (constantly fake-channels)]+ (mt/with-dynamic-fn-redefs [channel.settings/slack-configured? (constantly true)+ channel.settings/slack-cached-channels-and-usernames (constantly fake-channels)](testing "Slack alert can be created"(is (= {:output "success"}(invoke-tool base-data))))@@ -42,8 +42,8 @@(let [invoke-tool #(mt/with-current-user (mt/user->id :rasta)(metabot.tools.create-alert/create-alert %))base-data (alert-data card-id)]- (with-redefs [channel.settings/slack-configured? (constantly true)- channel.settings/slack-cached-channels-and-usernames (constantly fake-channels)]+ (mt/with-dynamic-fn-redefs [channel.settings/slack-configured? (constantly true)+ channel.settings/slack-cached-channels-and-usernames (constantly fake-channels)](testing "Return an error message if the card-id is invalid"(is (= {:error "invalid card_id"}(invoke-tool (update base-data :card-id str)))))@@ -66,11 +66,11 @@(metabot.tools.create-alert/create-alert %))base-data (alert-data card-id)](testing "Slack alert fails when Slack is not configured"- (with-redefs [channel.settings/slack-configured? (constantly false)]+ (mt/with-dynamic-fn-redefs [channel.settings/slack-configured? (constantly false)](is (= {:error "slack is not configured. Ask an admin to set up slack notifications in Metabase settings."}(invoke-tool base-data)))))(testing "Slack alert fails when channel does not exist"- (with-redefs [channel.settings/slack-configured? (constantly true)- channel.settings/slack-cached-channels-and-usernames (constantly {:channels []})]+ (mt/with-dynamic-fn-redefs [channel.settings/slack-configured? (constantly true)+ channel.settings/slack-cached-channels-and-usernames (constantly {:channels []})](is (= {:error "no slack channel found with this name"}(invoke-tool (assoc base-data :slack-channel "no-such-channel")))))))))diff --git a/test/metabase/metabot/tools/document_test.clj b/test/metabase/metabot/tools/document_test.cljindex 7b5473f3b87..72c576398ed 100644--- a/test/metabase/metabot/tools/document_test.clj+++ b/test/metabase/metabot/tools/document_test.clj@@ -7,14 +7,15 @@[metabase.metabot.tools.shared :as shared][metabase.metabot.tools.sql.create :as create-sql-query-tools][metabase.query-processor :as qp]+ [metabase.test :as mt][metabase.warehouses.core :as warehouses]))(deftest document-schema-collect-tool-test(testing "returns schema/instructions when one database reference is present"- (with-redefs [shared/current-context (fn [] {:references {"database:1" "Test Database"}})- warehouses/get-database (fn [_] {:id 1 :engine "h2"})- table-utils/schema-full (fn [_]- "CREATE TABLE TestTable (\n TestColumn varchar\n);")]+ (mt/with-dynamic-fn-redefs [shared/current-context (fn [] {:references {"database:1" "Test Database"}})+ warehouses/get-database (fn [_] {:id 1 :engine "h2"})+ table-utils/schema-full (fn [_]+ "CREATE TABLE TestTable (\n TestColumn varchar\n);")](let [result (document-tools/document-schema-collect-tool {})](is (string? (:output result)))(is (re-find #"CREATE TABLE TestTable" (:output result)))@@ -25,30 +26,30 @@(:structured-output result))))))(testing "returns missing-database message when no database references are present"- (with-redefs [shared/current-context (fn [] {:references {}})]+ (mt/with-dynamic-fn-redefs [shared/current-context (fn [] {:references {}})](let [result (document-tools/document-schema-collect-tool {})](is (= "You must `@` mention a database to use when not querying an existing model"(:output result))))))(testing "returns multiple-database message when more than one database is referenced"- (with-redefs [shared/current-context (fn [] {:references {"database:1" "Test DB 1"- "database:2" "Test DB 2"}})]+ (mt/with-dynamic-fn-redefs [shared/current-context (fn [] {:references {"database:1" "Test DB 1"+ "database:2" "Test DB 2"}})](let [result (document-tools/document-schema-collect-tool {})](is (= "You can only `@` mention one database when generating SQL"(:output result)))))))(deftest document-construct-sql-chart-tool-test(testing "builds chart draft payload from SQL query"- (with-redefs [create-sql-query-tools/create-sql-query- (fn [_]- {:validation-result {:valid? true- :dialect "postgres"}- :action-result {:query-id "q-1"- :query {:database 1- :type "native"- :native {:query "SELECT * FROM test"- :template-tags {}}}}})- qp/process-query (fn [_] nil)]+ (mt/with-dynamic-fn-redefs [create-sql-query-tools/create-sql-query+ (fn [_]+ {:validation-result {:valid? true+ :dialect "postgres"}+ :action-result {:query-id "q-1"+ :query {:database 1+ :type "native"+ :native {:query "SELECT * FROM test"+ :template-tags {}}}}})+ qp/process-query (fn [_] nil)](let [result (document-tools/document-construct-sql-chart-tool{:database_id 1:name "Test Name"@@ -72,11 +73,11 @@(:dataset_query structured))))))(testing "returns instructions when SQL validation fails"- (with-redefs [create-sql-query-tools/create-sql-query- (fn [_]- {:validation-result {:valid? false- :dialect "postgres"- :error-message "syntax error near FROM"}})]+ (mt/with-dynamic-fn-redefs [create-sql-query-tools/create-sql-query+ (fn [_]+ {:validation-result {:valid? false+ :dialect "postgres"+ :error-message "syntax error near FROM"}})](let [result (document-tools/document-construct-sql-chart-tool{:database_id 1:name "Test Name"@@ -91,17 +92,17 @@(is (re-find #"syntax error near FROM" (:output result))))))(testing "returns instructions when query processor rejects generated SQL"- (with-redefs [create-sql-query-tools/create-sql-query- (fn [_]- {:validation-result {:valid? true- :dialect "postgres"}- :action-result {:query-id "q-1"- :query {:database 1- :type "native"- :native {:query "SELECT * FROM missing_table"- :template-tags {}}}}})- qp/process-query (fn [_]- (throw (ex-info "Table \"missing_table\" does not exist" {})))]+ (mt/with-dynamic-fn-redefs [create-sql-query-tools/create-sql-query+ (fn [_]+ {:validation-result {:valid? true+ :dialect "postgres"}+ :action-result {:query-id "q-1"+ :query {:database 1+ :type "native"+ :native {:query "SELECT * FROM missing_table"+ :template-tags {}}}}})+ qp/process-query (fn [_]+ (throw (ex-info "Table \"missing_table\" does not exist" {})))](let [result (document-tools/document-construct-sql-chart-tool{:database_id 1:name "Test Name"@@ -117,11 +118,11 @@(deftest document-construct-model-chart-tool-test(testing "builds chart draft payload from model query"- (with-redefs [construct-tools/construct-notebook-query-tool- (fn [_]- {:structured-output {:query-id "3"- :query {:database 1- :type "query"}}})]+ (mt/with-dynamic-fn-redefs [construct-tools/construct-notebook-query-tool+ (fn [_]+ {:structured-output {:query-id "3"+ :query {:database 1+ :type "query"}}})](let [result (document-tools/document-construct-model-chart-tool{:name "Test Name":description "Test Desc"diff --git a/test/metabase/metabot/tools/search_test.clj b/test/metabase/metabot/tools/search_test.cljindex 62a0d603fbf..4ab716b0985 100644--- a/test/metabase/metabot/tools/search_test.clj+++ b/test/metabase/metabot/tools/search_test.clj@@ -249,17 +249,17 @@perms/sandboxed-user? (fn [] false)api/*current-user-id* 1](testing ":search-native-query is included in context when true"- (with-redefs [search-core/search (fn [context]- (is (true? (:search-native-query context)))- {:data []})]+ (mt/with-dynamic-fn-redefs [search-core/search (fn [context]+ (is (true? (:search-native-query context)))+ {:data []})](search/search {:term-queries ["test"]:entity-types ["card"]:search-native-query true})))(testing ":search-native-query is not included in context when nil or false"- (with-redefs [search-core/search (fn [context]- (is (not (contains? context :search-native-query)))- {:data []})]+ (mt/with-dynamic-fn-redefs [search-core/search (fn [context]+ (is (not (contains? context :search-native-query)))+ {:data []})](search/search {:term-queries ["test"]:entity-types ["card"]:search-native-query false})diff --git a/test/metabase/metabot/tools/subscriptions_test.clj b/test/metabase/metabot/tools/subscriptions_test.cljindex c4c05738b65..4d7c01bfaf8 100644--- a/test/metabase/metabot/tools/subscriptions_test.clj+++ b/test/metabase/metabot/tools/subscriptions_test.clj@@ -22,8 +22,8 @@(deftest create-dashboard-subscription-happy-path-test(testing "valid dashboard, valid user email, valid schedule → success"(let [captured-args (atom nil)]- (with-redefs [agent-subscriptions/create-dashboard-subscription- (fn [args] (reset! captured-args args) {:output "success"})]+ (mt/with-dynamic-fn-redefs [agent-subscriptions/create-dashboard-subscription+ (fn [args] (reset! captured-args args) {:output "success"})](mt/with-current-user (mt/user->id :crowberto)(mt/with-temp [:model/Dashboard {dash-id :id} {:name "Test Dashboard"}](let [email (:email (mt/fetch-user :crowberto))@@ -47,11 +47,11 @@(deftest create-dashboard-subscription-unknown-email-test(testing "unknown email → 'no user with this email found'"- (with-redefs [agent-subscriptions/create-dashboard-subscription- (fn [{:keys [email]}]- (if (= email "[email protected]")- {:output "no user with this email found"}- {:output "success"}))]+ (mt/with-dynamic-fn-redefs [agent-subscriptions/create-dashboard-subscription+ (fn [{:keys [email]}]+ (if (= email "[email protected]")+ {:output "no user with this email found"}+ {:output "success"}))](mt/with-current-user (mt/user->id :crowberto)(mt/with-temp [:model/Dashboard {dash-id :id} {:name "Test Dashboard"}](let [result (agent-subscriptions/create-dashboard-subscription-tool@@ -62,11 +62,11 @@(deftest create-dashboard-subscription-nonexistent-dashboard-test(testing "nonexistent dashboard → 404 or error message"- (with-redefs [agent-subscriptions/create-dashboard-subscription- (fn [{:keys [dashboard-id]}]- (if (= dashboard-id 999999)- {:output "no dashboard with this dashboard_id found"}- {:output "success"}))]+ (mt/with-dynamic-fn-redefs [agent-subscriptions/create-dashboard-subscription+ (fn [{:keys [dashboard-id]}]+ (if (= dashboard-id 999999)+ {:output "no dashboard with this dashboard_id found"}+ {:output "success"}))](mt/with-current-user (mt/user->id :crowberto)(let [result (agent-subscriptions/create-dashboard-subscription-tool{:dashboard_id 999999@@ -77,8 +77,8 @@(deftest create-dashboard-subscription-schedule-keywords-test(testing "schedule keywords are converted from snake_case to kebab-case"(let [captured-args (atom nil)]- (with-redefs [agent-subscriptions/create-dashboard-subscription- (fn [args] (reset! captured-args args) {:output "success"})]+ (mt/with-dynamic-fn-redefs [agent-subscriptions/create-dashboard-subscription+ (fn [args] (reset! captured-args args) {:output "success"})](mt/with-current-user (mt/user->id :crowberto)(agent-subscriptions/create-dashboard-subscription-tool{:dashboard_id 1@@ -101,9 +101,9 @@(deftest create-dashboard-subscription-slack-happy-path-test(testing "valid dashboard, Slack channel, daily schedule → success"(mt/with-model-cleanup [:model/Pulse]- (with-redefs [channel.settings/slack-configured? (constantly true)- channel.settings/slack-cached-channels-and-usernames- (constantly {:channels [{:display-name "#data-team" :name "data-team" :id "C123"}]})]+ (mt/with-dynamic-fn-redefs [channel.settings/slack-configured? (constantly true)+ channel.settings/slack-cached-channels-and-usernames+ (constantly {:channels [{:display-name "#data-team" :name "data-team" :id "C123"}]})](mt/with-current-user (mt/user->id :crowberto)(mt/with-temp [:model/Dashboard {dash-id :id} {:name "Test Dashboard"}:model/Card {card-id :id} {}@@ -120,9 +120,9 @@(deftest create-dashboard-subscription-slack-monthly-schedule-test(testing "Slack subscription with monthly schedule → success"(mt/with-model-cleanup [:model/Pulse]- (with-redefs [channel.settings/slack-configured? (constantly true)- channel.settings/slack-cached-channels-and-usernames- (constantly {:channels [{:display-name "#data-team" :name "data-team" :id "C123"}]})]+ (mt/with-dynamic-fn-redefs [channel.settings/slack-configured? (constantly true)+ channel.settings/slack-cached-channels-and-usernames+ (constantly {:channels [{:display-name "#data-team" :name "data-team" :id "C123"}]})](mt/with-current-user (mt/user->id :crowberto)(mt/with-temp [:model/Dashboard {dash-id :id} {:name "Test Dashboard"}:model/Card {card-id :id} {}@@ -140,7 +140,7 @@(deftest create-dashboard-subscription-slack-required-test(testing "empty slack_channel → error"- (with-redefs [channel.settings/slack-configured? (constantly true)]+ (mt/with-dynamic-fn-redefs [channel.settings/slack-configured? (constantly true)](mt/with-current-user (mt/user->id :crowberto)(mt/with-temp [:model/Dashboard {dash-id :id} {:name "Test Dashboard"}](let [result (agent-subscriptions/create-dashboard-subscription-tool@@ -151,7 +151,7 @@(deftest create-dashboard-subscription-slack-not-configured-test(testing "Slack not configured → error"- (with-redefs [channel.settings/slack-configured? (constantly false)]+ (mt/with-dynamic-fn-redefs [channel.settings/slack-configured? (constantly false)](mt/with-current-user (mt/user->id :crowberto)(mt/with-temp [:model/Dashboard {dash-id :id} {:name "Test Dashboard"}](let [result (agent-subscriptions/create-dashboard-subscription-tool@@ -163,8 +163,8 @@(deftest create-dashboard-subscription-slack-channel-not-found-test(testing "nonexistent Slack channel → error"- (with-redefs [channel.settings/slack-configured? (constantly true)- channel.settings/slack-cached-channels-and-usernames (constantly {:channels []})]+ (mt/with-dynamic-fn-redefs [channel.settings/slack-configured? (constantly true)+ channel.settings/slack-cached-channels-and-usernames (constantly {:channels []})](mt/with-current-user (mt/user->id :crowberto)(mt/with-temp [:model/Dashboard {dash-id :id} {:name "Test Dashboard"}:model/Card {card-id :id} {}diff --git a/test/metabase/metabot/tools/transforms_test.clj b/test/metabase/metabot/tools/transforms_test.cljindex 5088d21441c..0b29ee5b9fa 100644--- a/test/metabase/metabot/tools/transforms_test.clj+++ b/test/metabase/metabot/tools/transforms_test.clj@@ -80,10 +80,10 @@:source {:type "query" :query "SELECT 1"}}:message "Transform updated successfully."}:data-parts [{:type :data :data-type "transform_suggestion" :version 1}]}]- (with-redefs [transforms-write/write-transform-sql (fn [_] base-result)- deps/check-transform-dependencies (fn [_] {:structured_output {:success true- :bad_transforms []- :bad_questions nil}})]+ (mt/with-dynamic-fn-redefs [transforms-write/write-transform-sql (fn [_] base-result)+ deps/check-transform-dependencies (fn [_] {:structured_output {:success true+ :bad_transforms []+ :bad_questions nil}})](let [result (binding [shared/*memory-atom* memory-atom](agent-transforms/write-transform-sql-tool{:transform_id 1@@ -99,14 +99,14 @@:source {:type "query" :query "SELECT id FROM orders"}}:message "Transform updated successfully."}:data-parts [{:type :data :data-type "transform_suggestion" :version 1}]}]- (with-redefs [transforms-write/write-transform-sql (fn [_] base-result)- deps/check-transform-dependencies (fn [_]- {:structured_output- {:success false- :bad_transform_count 1- :bad_transforms [{:transform {:id 2 :name "Downstream Transform"}- :errors ["Column 'total' not found"]}]- :bad_questions nil}})]+ (mt/with-dynamic-fn-redefs [transforms-write/write-transform-sql (fn [_] base-result)+ deps/check-transform-dependencies (fn [_]+ {:structured_output+ {:success false+ :bad_transform_count 1+ :bad_transforms [{:transform {:id 2 :name "Downstream Transform"}+ :errors ["Column 'total' not found"]}]+ :bad_questions nil}})](let [result (binding [shared/*memory-atom* memory-atom](agent-transforms/write-transform-sql-tool{:transform_id 1@@ -125,17 +125,17 @@:source {:type "query" :query "SELECT id FROM orders"}}:message "Transform updated successfully."}:data-parts [{:type :data :data-type "transform_suggestion" :version 1}]}]- (with-redefs [transforms-write/write-transform-sql (fn [_] base-result)- deps/check-transform-dependencies (fn [_]- {:structured_output- {:success false- :bad_transform_count 0- :bad_transforms []- :bad_question_count 2- :bad_questions [{:question {:id 10 :name "Revenue Report"}- :errors ["Column 'total' not found"]}- {:question {:id 11 :name "Monthly Summary"}- :errors ["Column 'total' not found"]}]}})]+ (mt/with-dynamic-fn-redefs [transforms-write/write-transform-sql (fn [_] base-result)+ deps/check-transform-dependencies (fn [_]+ {:structured_output+ {:success false+ :bad_transform_count 0+ :bad_transforms []+ :bad_question_count 2+ :bad_questions [{:question {:id 10 :name "Revenue Report"}+ :errors ["Column 'total' not found"]}+ {:question {:id 11 :name "Monthly Summary"}+ :errors ["Column 'total' not found"]}]}})](let [result (binding [shared/*memory-atom* memory-atom](agent-transforms/write-transform-sql-tool{:transform_id 1@@ -155,8 +155,8 @@:source {:type "query" :query "SELECT 1"}}:message "Transform updated successfully."}:data-parts [{:type :data :data-type "transform_suggestion" :version 1}]}]- (with-redefs [transforms-write/write-transform-sql (fn [_] base-result)- deps/check-transform-dependencies (fn [_] (throw (Exception. "DB connection failed")))]+ (mt/with-dynamic-fn-redefs [transforms-write/write-transform-sql (fn [_] base-result)+ deps/check-transform-dependencies (fn [_] (throw (Exception. "DB connection failed")))](let [result (binding [shared/*memory-atom* memory-atom](agent-transforms/write-transform-sql-tool{:transform_id 1@@ -173,8 +173,8 @@:source {:type "query" :query "SELECT 1"}}:message "Transform created successfully."}:data-parts [{:type :data :data-type "transform_suggestion" :version 1}]}]- (with-redefs [transforms-write/write-transform-sql (fn [_] base-result)- deps/check-transform-dependencies (fn [_] (reset! dep-called? true) nil)]+ (mt/with-dynamic-fn-redefs [transforms-write/write-transform-sql (fn [_] base-result)+ deps/check-transform-dependencies (fn [_] (reset! dep-called? true) nil)](let [result (binding [shared/*memory-atom* memory-atom](agent-transforms/write-transform-sql-tool{:edit_action {:mode "replace" :new_content "SELECT 1"}diff --git a/test/metabase/metabot/tools_test.clj b/test/metabase/metabot/tools_test.cljindex f7326f7a8b4..05b97dc1bef 100644--- a/test/metabase/metabot/tools_test.clj+++ b/test/metabase/metabot/tools_test.clj@@ -6,7 +6,8 @@[metabase.metabot.scope :as scope][metabase.metabot.tools :as agent-tools][metabase.metabot.tools.charts.create :as create-chart-tools]- [metabase.metabot.tools.construct :as construct]))+ [metabase.metabot.tools.construct :as construct]+ [metabase.test :as mt]))(deftest all-tools-test(testing "profile tools are vars with required metadata"@@ -117,21 +118,21 @@(testing "construct_notebook_query evaluates a program and creates a chart"(let [program-captured (atom nil)chart-called (atom nil)]- (with-redefs [construct/execute-program (fn [_source-entity _referenced-entities program]- (reset! program-captured program)- {:structured-output {:query-id "q-1"- :query {:database 1}- :result-columns []}- :instructions "Query created."})- create-chart-tools/create-chart (fn [args]- (reset! chart-called args)- {:chart-id "c-1"- :chart-type :table- :chart-link "metabase://chart/c-1"- :chart-content "<chart/>"- :query-id (:query-id args)- :reactions [{:type :metabot.reaction/redirect- :url "/question#hash"}]})]+ (mt/with-dynamic-fn-redefs [construct/execute-program (fn [_source-entity _referenced-entities program]+ (reset! program-captured program)+ {:structured-output {:query-id "q-1"+ :query {:database 1}+ :result-columns []}+ :instructions "Query created."})+ create-chart-tools/create-chart (fn [args]+ (reset! chart-called args)+ {:chart-id "c-1"+ :chart-type :table+ :chart-link "metabase://chart/c-1"+ :chart-content "<chart/>"+ :query-id (:query-id args)+ :reactions [{:type :metabot.reaction/redirect+ :url "/question#hash"}]})](let [result (agent-tools/construct-notebook-query-tool{:reasoning "check seats":source_entity {:type "table" :id 6}diff --git a/test/metabase/model_persistence/api_test.clj b/test/metabase/model_persistence/api_test.cljindex 5e738eb6435..ce36ec95a38 100644--- a/test/metabase/model_persistence/api_test.clj+++ b/test/metabase/model_persistence/api_test.clj@@ -103,6 +103,7 @@(.setProperty "org.quartz.threadPool.threadCount" "6")(.setProperty "org.quartz.threadPool.class" "org.quartz.simpl.SimpleThreadPool"))))];; a binding won't work since we need to cross thread boundaries+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}(with-redefs [task/scheduler (constantly sched)](try(qs/standby sched)diff --git a/test/metabase/model_persistence/task/persist_refresh_test.clj b/test/metabase/model_persistence/task/persist_refresh_test.cljindex 09161029cb7..189417d0d9d 100644--- a/test/metabase/model_persistence/task/persist_refresh_test.clj+++ b/test/metabase/model_persistence/task/persist_refresh_test.clj@@ -127,12 +127,12 @@(refresh! [_ _database _definition _card]{:state :success})(unpersist! [_ _database _persisted-info]))- original-update! t2/update!]+ original-update! (mt/original-fn #'t2/update!)](testing "If saving the `persisted` (or `error`) state fails..."- (with-redefs [t2/update! (fn [model id update]- (when (= "persisted" (:state update))- (throw (ex-info "simulated error" {})))- (original-update! model id update))]+ (mt/with-dynamic-fn-redefs [t2/update! (fn [model id update]+ (when (= "persisted" (:state update))+ (throw (ex-info "simulated error" {})))+ (original-update! model id update))](is (thrown-with-msg? clojure.lang.ExceptionInfo #"simulated error"(#'task.persist-refresh/refresh-tables! (u/the-id db) test-refresher))))(testing "the PersistedInfo is left in the `refreshing` state"@@ -259,8 +259,8 @@(testing "send an email if persist-refresh fails"(let [email-sent (atom false)];; TODO -- a real test that actually made sure this function worked instead of swapping it out would be nice.- (with-redefs [task.persist-refresh/publish-refresh-error-event! (fn [& _args]- (reset! email-sent true))]+ (mt/with-dynamic-fn-redefs [task.persist-refresh/publish-refresh-error-event! (fn [& _args]+ (reset! email-sent true))](#'task.persist-refresh/save-task-history! "persist-refresh" (mt/id)(fn []{:error-details ["some-error"]}))diff --git a/test/metabase/model_persistence/task/persist_refresh_write_pool_test.clj b/test/metabase/model_persistence/task/persist_refresh_write_pool_test.cljindex 9a6d715510a..a1247e296f8 100644--- a/test/metabase/model_persistence/task/persist_refresh_write_pool_test.clj+++ b/test/metabase/model_persistence/task/persist_refresh_write_pool_test.clj@@ -11,11 +11,11 @@(mt/test-drivers (mt/normal-driver-select {:+parent :sql-jdbc, :+features [:persist-models]})(let [db-id (mt/id)write-cache-key [db-id :write-data]]- (with-redefs [driver.conn/effective-connection-type- (fn [_database]- (if (= driver.conn/*connection-type* :write-data)- :write-data- :default))]+ (mt/with-dynamic-fn-redefs [driver.conn/effective-connection-type+ (fn [_database]+ (if (= driver.conn/*connection-type* :write-data)+ :write-data+ :default))](try(sql-jdbc.conn/invalidate-pool-for-db! (mt/db))(testing "write pool does not exist before refresh"@@ -37,11 +37,11 @@(mt/test-drivers (mt/normal-driver-select {:+parent :sql-jdbc, :+features [:persist-models]})(let [db-id (mt/id)write-cache-key [db-id :write-data]]- (with-redefs [driver.conn/effective-connection-type- (fn [_database]- (if (= driver.conn/*connection-type* :write-data)- :write-data- :default))]+ (mt/with-dynamic-fn-redefs [driver.conn/effective-connection-type+ (fn [_database]+ (if (= driver.conn/*connection-type* :write-data)+ :write-data+ :default))](try(sql-jdbc.conn/invalidate-pool-for-db! (mt/db))(testing "write pool does not exist before prune"diff --git a/test/metabase/model_persistence/test_util.clj b/test/metabase/model_persistence/test_util.cljindex e02786ac13d..8e01255e48e 100644--- a/test/metabase/model_persistence/test_util.clj+++ b/test/metabase/model_persistence/test_util.clj@@ -4,12 +4,13 @@[metabase.model-persistence.models.persisted-info :as persisted-info][metabase.model-persistence.task.persist-refresh :as task.persist-refresh][metabase.test.data :as data]- [metabase.test.util :as tu]))+ [metabase.test.util :as tu]+ [metabase.test.util.dynamic-redefs :as dynamic-redefs]))(defn do-with-persistence-enabled]+ (dynamic-redefs/with-dynamic-fn-redefs [persisted-info/default-persistent-info-state (fn [] "creating")](ddl.i/check-can-persist (data/db))(persisted-info/ready-database! (data/id))(let [persist-fn (fn persist-fn []diff --git a/test/metabase/models/humanization_test.clj b/test/metabase/models/humanization_test.cljindex dab13aa4b00..9c544c476e8 100644--- a/test/metabase/models/humanization_test.clj+++ b/test/metabase/models/humanization_test.clj@@ -7,7 +7,7 @@[toucan2.core :as t2]))(defn- get-humanized-display-name! [actual-name strategy]- (with-redefs [humanization/humanization-strategy (constantly strategy)]+ (mt/with-dynamic-fn-redefs [humanization/humanization-strategy (constantly strategy)](mt/with-temp [:model/Table {table-id :id} {:name actual-name}](t2/select-one-fn :display_name :model/Table, :id table-id))))diff --git a/test/metabase/models/on_demand_test.clj b/test/metabase/models/on_demand_test.cljindex b8589e3d9c1..1060c8281b5 100644--- a/test/metabase/models/on_demand_test.clj+++ b/test/metabase/models/on_demand_test.clj@@ -15,8 +15,8 @@of Fields that should have been updated. Returns the set of updated Field names."[f](let [updated-field-names (atom #{})]- (with-redefs [field-values/create-or-update-full-field-values! (fn [field]- (swap! updated-field-names conj (:name field)))]+ (mt/with-dynamic-fn-redefs [field-values/create-or-update-full-field-values! (fn [field]+ (swap! updated-field-names conj (:name field)))](f updated-field-names)@updated-field-names)))diff --git a/test/metabase/models/util/spec_update_test.clj b/test/metabase/models/util/spec_update_test.cljindex 448f4d4a372..d4d943d8139 100644--- a/test/metabase/models/util/spec_update_test.clj+++ b/test/metabase/models/util/spec_update_test.clj@@ -2,6 +2,7 @@(:require[clojure.test :refer :all][metabase.models.util.spec-update :as spec-update]+ [metabase.test :as mt][toucan2.core :as t2]))(defn do-track-operations!@@ -12,10 +13,10 @@track! (fn [op args](swap! operations conj (cons op args))1)]- (with-redefs [t2/insert! (fn [& args] (track! :insert! args))- t2/insert-returning-pk! (fn [& args] (track! :insert-returning-pk! args) (swap! id-counter inc) @id-counter)- t2/update! (fn [& args] (track! :update! args))- t2/delete! (fn [& args] (track! :delete! args))]+ (mt/with-dynamic-fn-redefs [t2/insert! (fn [& args] (track! :insert! args))+ t2/insert-returning-pk! (fn [& args] (track! :insert-returning-pk! args) (swap! id-counter inc) @id-counter)+ t2/update! (fn [& args] (track! :update! args))+ t2/delete! (fn [& args] (track! :delete! args))](f)@operations)))diff --git a/test/metabase/notification/api/notification_test.clj b/test/metabase/notification/api/notification_test.cljindex 5a36c2e57a5..3dc64accf72 100644--- a/test/metabase/notification/api/notification_test.clj+++ b/test/metabase/notification/api/notification_test.clj@@ -681,7 +681,7 @@[:model/Collection {collection-id :id} {:personal_owner_id (:id user)}:model/Card {card-id :id} {:collection_id collection-id}](let [create-notification! (fn [user-or-id expected-status]- (with-redefs [notification/send-notification! (fn [& _args] :done)]+ (mt/with-dynamic-fn-redefs [notification/send-notification! (fn [& _args] :done)](mt/user-http-request user-or-id :post expected-status "notification/send"{:payload_type "notification/card":creator_id (mt/user->id :rasta)diff --git a/test/metabase/notification/payload/impl/card_test.clj b/test/metabase/notification/payload/impl/card_test.cljindex 7b7a28db6f4..e59fb84a10f 100644--- a/test/metabase/notification/payload/impl/card_test.clj+++ b/test/metabase/notification/payload/impl/card_test.clj@@ -535,7 +535,7 @@[notification {:handlers [@notification.tu/default-email-handlernotification.tu/default-slack-handler]}]- (let [original-render-noti (var-get #'channel/render-notification)]+ (let [original-render-noti (mt/original-fn #'channel/render-notification)](with-redefs [channel/render-notification (fn [& args](if (= :channel/slack (first args))(throw (ex-info "Slack failed" {}))diff --git a/test/metabase/notification/payload/impl/system_event_test.clj b/test/metabase/notification/payload/impl/system_event_test.cljindex 086e4535ffb..f3268be99f9 100644--- a/test/metabase/notification/payload/impl/system_event_test.clj+++ b/test/metabase/notification/payload/impl/system_event_test.clj@@ -133,8 +133,8 @@"Ngoc")(testing "with sso enabled"- (with-redefs [sso.settings/sso-enabled? (constantly true)- session.settings/enable-password-login (constantly false)]+ (mt/with-dynamic-fn-redefs [sso.settings/sso-enabled? (constantly true)+ session.settings/enable-password-login (constantly false)](check false"You're invited to join SuperStar's Metabase"[#"<a[^>]*href=\"https?://metabase\.com/auth/login\"[^>]*>Join now</a>"]diff --git a/test/metabase/notification/send_test.clj b/test/metabase/notification/send_test.cljindex eff780f6893..eb7865051e6 100644--- a/test/metabase/notification/send_test.clj+++ b/test/metabase/notification/send_test.clj@@ -56,13 +56,13 @@[:context :map][:payload :map]])renders (atom [])]- (mt/with-dynamic-fn-redefs [channel/render-notification (fn [channel-type notification-payload {:keys [template recipients]}]- (swap! renders conj {:channel-type channel-type- :notification-payload notification-payload- :template template- :recipients recipients})+ (with-redefs [channel/render-notification (fn [channel-type notification-payload {:keys [template recipients]}]+ (swap! renders conj {:channel-type channel-type+ :notification-payload notification-payload+ :template template+ :recipients recipients});; rendered messages are recipients- recipients)]+ recipients)](testing "channel/send! are called on rendered messages"(is (=? {:channel/metabase-test [{:type :notification-recipient/user :user_id (mt/user->id :crowberto)}{:type :notification-recipient/user :user_id (mt/user->id :rasta)}]}@@ -157,7 +157,7 @@(if (= @retry-count 1)(throw (Exception. "test-exception"))(reset! send-args args)))]- (mt/with-dynamic-fn-redefs [channel/send! send!]+ (with-redefs [channel/send! send!](#'notification.send/send-notification-sync! n))(is (some? @send-args))(is (=? {:task "channel-send"@@ -183,8 +183,8 @@(testing "and record exception in task history"(let [send! (fn [& _args](throw (ex-info "Failed to send" {:metadata 42})))]- (mt/with-dynamic-fn-redefs [notification.send/should-skip-retry? (constantly true)- channel/send! send!]+ (with-redefs [notification.send/should-skip-retry? (constantly true)+ channel/send! send!](#'notification.send/send-notification-sync! n))(is (=? {:task "channel-send":status :failed@@ -218,7 +218,7 @@(testing "send email succeeds hiding SMTP host not set error"(let [[hook state] (rt/retry-analytics-config-hook)](binding [retry/*test-time-config-hook* hook]- (with-redefs [email/send-email! (fn [& _] (throw (ex-info "Bumm!" {:cause :smtp-host-not-set})))]+ (mt/with-dynamic-fn-redefs [email/send-email! (fn [& _] (throw (ex-info "Bumm!" {:cause :smtp-host-not-set})))](mt/with-temporary-setting-values [email-smtp-host "fake_smtp_host"email-smtp-port 587](mt/reset-inbox!)@@ -255,15 +255,15 @@(testing "post slack message succeeds w/o retry"(let [[hook state] (rt/retry-analytics-config-hook)](binding [retry/*test-time-config-hook* hook]- (with-redefs [slack/post-chat-message! (constantly nil)]+ (mt/with-dynamic-fn-redefs [slack/post-chat-message! (constantly nil)](#'notification.send/channel-send-retrying! 1 :notification/card {:channel_type :channel/slack} fake-slack-notification)(is (= {:success true, :retries 0} @state))))))(testing "post slack message succeeds hiding token error, doesn't retry"(let [[hook state] (rt/retry-analytics-config-hook)](binding [retry/*test-time-config-hook* hook]- (with-redefs [slack/post-chat-message! (fn [& _]- (throw (ex-info "Slack API error: token_revoked"- {:error-type :slack/invalid-token})))]+ (mt/with-dynamic-fn-redefs [slack/post-chat-message! (fn [& _]+ (throw (ex-info "Slack API error: token_revoked"+ {:error-type :slack/invalid-token})))](#'notification.send/channel-send-retrying! 1 :notification/card {:channel_type :channel/slack} fake-slack-notification)(is (= {:success false, :retries 0} @state))))))(testing "post slack message fails b/c retry limit"@@ -281,10 +281,10 @@(testing "post slack message to missing channel fails without retry"(let [[hook state] (rt/retry-analytics-config-hook)](binding [retry/*test-time-config-hook* hook]- (with-redefs [slack/post-chat-message! (fn [& _]- (throw (ex-info "Channel not found"- {:error-type :slack/channel-not-found}))- nil)]+ (mt/with-dynamic-fn-redefs [slack/post-chat-message! (fn [& _]+ (throw (ex-info "Channel not found"+ {:error-type :slack/channel-not-found}))+ nil)](#'notification.send/channel-send-retrying! 1 :notification/card {:channel_type :channel/slack} fake-slack-notification)(is (= {:success false, :retries 0} @state))))))))@@ -440,7 +440,7 @@(is (thrown? AssertionError (#'notification.send/avg-interval-seconds "0 0 12 * * ? *" 0))))(testing "handles one-off schedules correctly"- (with-redefs [notification.send/cron->next-execution-times (fn [_ _] [(t/instant)])]+ (mt/with-dynamic-fn-redefs [notification.send/cron->next-execution-times (fn [_ _] [(t/instant)])](is (= 10 (#'notification.send/avg-interval-seconds "0 0 12 * * ? *" 5))))))(deftest subscription->deadline-test@@ -477,6 +477,9 @@:done? (fn [cnt] (= cnt %)):interval-ms 10:timeout-ms 1000})]+ ;; dispatcher spawns its own worker threads that don't inherit *local-redefs* —+ ;; use with-redefs to swap the root so worker threads see the replacement.+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}(with-redefs [notification.send/send-notification-sync! (fn [notification];; fake latency(Thread/sleep 20)@@ -515,6 +518,8 @@(testing "error handling - worker errors don't crash the dispatcher"(reset! sent-notifications [])(let [error-thrown (atom false)]+ ;; dispatcher worker thread — see note above+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}(with-redefs [notification.send/send-notification-sync!(fn [notification](if (= "F" (:test-value notification))@@ -681,6 +686,9 @@(testing "if there are failure inside the notification thread pool, it should not exhaust the pool (#56379)"(let [noti-count (atom 0)queue-size (notification.settings/notification-thread-pool-size)]+ ;; notification thread pool workers don't inherit *local-redefs* — the root swap from+ ;; with-redefs is required so the patched fns are visible to the worker threads.+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}(with-redefs [notification.payload/notification-payload (fn [& _](assert false))notification.send/send-notification-sync! (fn [_notification]@@ -742,6 +750,8 @@dispatcher (#'notification.send/create-notification-dispatcher 2 queue)dispatch-fn (:dispatch-fn dispatcher)shutdown-fn (:shutdown-fn dispatcher)]+ ;; dispatcher spawns worker threads without our dynamic binding+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}(with-redefs [notification.send/send-notification-sync!(fn [notification];; Wait for the latch to be released before processingdiff --git a/test/metabase/parameters/chain_filter_test.clj b/test/metabase/parameters/chain_filter_test.cljindex 6ab99d11f29..df53b4027ae 100644--- a/test/metabase/parameters/chain_filter_test.clj+++ b/test/metabase/parameters/chain_filter_test.clj@@ -591,8 +591,8 @@(testing "should created a full FieldValues when constraints is `nil`";; warm up the cache(chain-filter categories.name nil)- (with-redefs [params.field-values/prepare-advanced-field-values (fn [& _args]- (assert false "Should not be called"))]+ (mt/with-dynamic-fn-redefs [params.field-values/prepare-advanced-field-values (fn [& _args]+ (assert false "Should not be called"))](is (= {:values [["African"] ["American"] ["Artisan"]]:has_more_values false}(take-n-values 3 (chain-filter categories.name nil))))@@ -602,8 +602,8 @@(field-values/clear-advanced-field-values-for-field! field-id);; warm up the cache(chain-filter categories.name {venues.price 4})- (with-redefs [params.field-values/prepare-advanced-field-values (fn [& _args]- (assert false "Should not be called"))]+ (mt/with-dynamic-fn-redefs [params.field-values/prepare-advanced-field-values (fn [& _args]+ (assert false "Should not be called"))](is (= {:values [["Japanese"] ["Steakhouse"]]:has_more_values false}(chain-filter categories.name {venues.price 4})))diff --git a/test/metabase/permissions/models/collection/graph_test.clj b/test/metabase/permissions/models/collection/graph_test.cljindex e8ca7618bca..7e15a760aee 100644--- a/test/metabase/permissions/models/collection/graph_test.clj+++ b/test/metabase/permissions/models/collection/graph_test.clj@@ -89,7 +89,7 @@(testing "Check that the audit collection has :read for admins (sparse - no :none entries)."(mt/with-non-admin-groups-no-root-collection-perms(mt/with-temp [:model/Collection collection {:namespace "analytics"}]- (with-redefs [audit/default-audit-collection (constantly collection)]+ (mt/with-dynamic-fn-redefs [audit/default-audit-collection (constantly collection)](is (= {:revision 0:groups {(u/the-id (perms-group/admin)) {:root :write, :COLLECTION :read}}}(replace-collection-ids collection (graph :clear-revisions? true, :collections [collection])))))))))@@ -100,7 +100,7 @@(testing "Cannot set write permissiosn with no feature flag"(mt/with-non-admin-groups-no-root-collection-perms(mt/with-temp [:model/Collection collection {:namespace "analytics"}]- (with-redefs [audit/default-audit-collection (constantly collection)]+ (mt/with-dynamic-fn-redefs [audit/default-audit-collection (constantly collection)](graph/update-graph! {:revision 0 :groups {(u/the-id (perms-group/all-users)) {(u/the-id collection) :write}}})(is (= {:revision 0:groups {(u/the-id (perms-group/admin)) {:root :write, :COLLECTION :read}}}@@ -108,7 +108,7 @@(testing "Cannot set read permissiosn with no feature flag"(mt/with-non-admin-groups-no-root-collection-perms(mt/with-temp [:model/Collection collection {:namespace "analytics"}]- (with-redefs [audit/default-audit-collection (constantly collection)]+ (mt/with-dynamic-fn-redefs [audit/default-audit-collection (constantly collection)](graph/update-graph! {:revision 0 :groups {(u/the-id (perms-group/all-users)) {(u/the-id collection) :read}}})(is (= {:revision 0:groups {(u/the-id (perms-group/admin)) {:root :write, :COLLECTION :read}}}diff --git a/test/metabase/permissions/models/data_permissions_test.clj b/test/metabase/permissions/models/data_permissions_test.cljindex b252bd05121..ade07872999 100644--- a/test/metabase/permissions/models/data_permissions_test.clj+++ b/test/metabase/permissions/models/data_permissions_test.clj@@ -826,8 +826,8 @@(t2/delete! :model/DataPermissions :group_id group-id :db_id db-id)(let [group (t2/select-one :model/PermissionsGroup :id group-id)];; Simulate EE returning :blocked for this group's view-data- (with-redefs [data-perms/new-database-view-data-permission-levels- (fn [group-ids] (zipmap group-ids (repeat :blocked)))]+ (mt/with-dynamic-fn-redefs [data-perms/new-database-view-data-permission-levels+ (fn [group-ids] (zipmap group-ids (repeat :blocked)))](data-perms/set-default-database-permissions! {:id db-id} [group])(is (= :no (t2/select-one-fn :perm_value :model/DataPermissions:group_id group-id :db_id db-id@@ -850,8 +850,8 @@(mt/with-temp [:model/Table {table-id-3 :id} {:db_id db-id :schema "PUBLIC" :active true}];; Delete auto-created view-data permission for table-id-3 so we can test set-default-table-permissions! directly(t2/delete! :model/DataPermissions :group_id group-id :table_id table-id-3 :perm_type :perms/view-data)- (with-redefs [data-perms/new-table-view-data-permission-levels- (fn [_db-id group-ids] (zipmap group-ids (repeat :blocked)))]+ (mt/with-dynamic-fn-redefs [data-perms/new-table-view-data-permission-levels+ (fn [_db-id group-ids] (zipmap group-ids (repeat :blocked)))](data-perms/set-default-table-permissions!{:id table-id-3 :db_id db-id :schema "PUBLIC"}[{:group-id group-id :perm-type :perms/view-data :default-value :unrestricted}]))diff --git a/test/metabase/permissions/models/permissions_test.clj b/test/metabase/permissions/models/permissions_test.cljindex 6418c4fc735..818fc3000fd 100644--- a/test/metabase/permissions/models/permissions_test.clj+++ b/test/metabase/permissions/models/permissions_test.clj@@ -251,7 +251,7 @@(mt/with-temp [:model/Collection {coll-id :id} {}:model/PermissionsGroup {tenant-group-id :id} {:is_tenant_group true}:model/PermissionsGroup {normal-group-id :id} {:is_tenant_group false}]- (with-redefs [audit.impl/is-collection-id-audit? (constantly true)]+ (mt/with-dynamic-fn-redefs [audit.impl/is-collection-id-audit? (constantly true)](is (thrown-with-msg? clojure.lang.ExceptionInfo #"Tenant groups cannot receive access to non-tenant collections\."(perms/grant-collection-read-permissions! tenant-group-id coll-id)));; does not throw - it's not a tenant groupdiff --git a/test/metabase/permissions/settings_test.clj b/test/metabase/permissions/settings_test.cljindex 2e1e8c0a123..5c90b74e748 100644--- a/test/metabase/permissions/settings_test.clj+++ b/test/metabase/permissions/settings_test.clj@@ -20,8 +20,8 @@", modal-setting-value: " modal-setting-value)(mt/with-current-user (mt/user->id :crowberto)(permissions.settings/show-updated-permission-modal! modal-setting-value)- (with-redefs [permissions.settings/instance-create-time (constantly instance-creation-time)- permissions.settings/v-fifty-migration-time (constantly fifty-migration-time)]+ (mt/with-dynamic-fn-redefs [permissions.settings/instance-create-time (constantly instance-creation-time)+ permissions.settings/v-fifty-migration-time (constantly fifty-migration-time)](let [expected-modal-value (get ->expected{:new-admin? (t/after? instance-creation-time fifty-migration-time):setting-value modal-setting-value})]@@ -36,8 +36,8 @@", banner-setting-value: " banner-setting-value)(mt/with-current-user (mt/user->id :crowberto)(permissions.settings/show-updated-permission-banner! banner-setting-value)- (with-redefs [permissions.settings/instance-create-time (constantly instance-creation-time)- permissions.settings/v-fifty-migration-time (constantly fifty-migration-time)]+ (mt/with-dynamic-fn-redefs [permissions.settings/instance-create-time (constantly instance-creation-time)+ permissions.settings/v-fifty-migration-time (constantly fifty-migration-time)](let [expected-banner-value (get ->expected{:new-admin? (t/after? instance-creation-time fifty-migration-time):setting-value banner-setting-value})]diff --git a/test/metabase/permissions/user_test.clj b/test/metabase/permissions/user_test.cljindex 2bfc645d5e1..e166008944e 100644--- a/test/metabase/permissions/user_test.clj+++ b/test/metabase/permissions/user_test.clj@@ -58,11 +58,11 @@(testing "Users with transforms read permission can create transform collections, even in the root"(mt/with-temp [:model/Collection {coll-id :id} {:name "Test transform coll" :namespace collection/transforms-ns}](testing "without permission"- (with-redefs [data-perms/is-data-analyst? (constantly false)]+ (mt/with-dynamic-fn-redefs [data-perms/is-data-analyst? (constantly false)](is (not (contains? (permissions.user/user-permissions-set (mt/user->id :lucky)) "/collection/namespace/transforms/root/")))(is (not (contains? (permissions.user/user-permissions-set (mt/user->id :lucky)) (format "/collection/%s" coll-id))))))(testing "with permission"- (with-redefs [data-perms/is-data-analyst? (constantly true)]+ (mt/with-dynamic-fn-redefs [data-perms/is-data-analyst? (constantly true)](is (contains? (permissions.user/user-permissions-set (mt/user->id :lucky)) "/collection/namespace/transforms/root/"))(is (contains? (permissions.user/user-permissions-set (mt/user->id :lucky)) (permissions.path/collection-readwrite-path coll-id))))))))diff --git a/test/metabase/premium_features/api_test.clj b/test/metabase/premium_features/api_test.cljindex 8a6162ae806..9fb63ee9785 100644--- a/test/metabase/premium_features/api_test.clj+++ b/test/metabase/premium_features/api_test.clj@@ -18,7 +18,7 @@(deftest get-token-status-test(testing "GET /api/premium-features/token/status"(testing "returns correctly"- (with-redefs [premium-features/token-status (constantly fake-token-status)]+ (mt/with-dynamic-fn-redefs [premium-features/token-status (constantly fake-token-status)](is (= fake-token-status(mt/user-http-request :crowberto :get 200 "premium-features/token/status")))))@@ -27,7 +27,7 @@(mt/user-http-request :rasta :get 403 "premium-features/token/status"))))(testing "returns 404 if no token is set"- (with-redefs [premium-features/token-status (constantly nil)]+ (mt/with-dynamic-fn-redefs [premium-features/token-status (constantly nil)](is (= "Not found."(mt/user-http-request :crowberto :get 404 "premium-features/token/status")))))))@@ -35,9 +35,9 @@(testing "POST /api/premium-features/token/refresh"(testing "clears cache and returns fresh token status"(let [cleared? (atom false)]- (with-redefs [premium-features/token-status (constantly fake-token-status)- premium-features/premium-embedding-token (constantly nil)- token-check/clear-cache! (fn [] (reset! cleared? true))]+ (mt/with-dynamic-fn-redefs [premium-features/token-status (constantly fake-token-status)+ premium-features/premium-embedding-token (constantly nil)+ token-check/clear-cache! (fn [] (reset! cleared? true))](is (=? (dissoc fake-token-status :trial)(mt/user-http-request :crowberto :post 200 "premium-features/token/refresh")))(is (true? @cleared?))))))@@ -47,8 +47,8 @@(mt/user-http-request :rasta :post 403 "premium-features/token/refresh"))))(testing "returns 404 if no token is set"- (with-redefs [premium-features/token-status (constantly nil)- premium-features/premium-embedding-token (constantly nil)]+ (mt/with-dynamic-fn-redefs [premium-features/token-status (constantly nil)+ premium-features/premium-embedding-token (constantly nil)](is (= "Not found."(mt/user-http-request :crowberto :post 404 "premium-features/token/refresh"))))))@@ -61,25 +61,27 @@(mt/with-temporary-setting-values [llm-proxy-base-url "https://proxy.example.com/llm/"ai-service-base-url "https://ai-service.example.com/"](let [request* (atom nil)]- (with-redefs [premium-features/token-status (constantly fake-token-status)- http/post (fn [url request-options]- (reset! request* [url request-options])- {:status 200})]+ (mt/with-dynamic-fn-redefs [premium-features/token-status (constantly fake-token-status)+ http/post (fn [url request-options]+ (reset! request* [url request-options])+ {:status 200})](mt/user-http-request :crowberto :post 200 "premium-features/token/refresh")(is (= [(str "https://ai-service.example.com/v1/invalidate-token-cache/" token){:throw-exceptions false}]@request*))))))))))(testing "POST /api/premium-features/token/refresh does not invalidate the AI service cache when it is not configured"- (with-redefs [premium-features/token-status (constantly fake-token-status)- premium-features/premium-embedding-token (constantly "proxy-token")- http/post (fn [& _]- (throw (ex-info "should not be called" {})))]+ (mt/with-dynamic-fn-redefs [premium-features/token-status (constantly fake-token-status)+ premium-features/premium-embedding-token (constantly "proxy-token")+ http/post (fn [& _]+ (throw (ex-info "should not be called" {})))](is (=? (dissoc fake-token-status :trial)(mt/user-http-request :crowberto :post 200 "premium-features/token/refresh"))))))(deftest token-refresh-sets-premium-features-cookie-test(testing "POST /api/premium-features/token/refresh sets the premium-features-last-updated cookie"+ ;; user-real-request hits a real Jetty server; handler thread doesn't inherit *local-redefs*.+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}(with-redefs [premium-features/token-status (constantly fake-token-status)premium-features/premium-embedding-token (constantly nil)](let [cs (cookies/cookie-store)]diff --git a/test/metabase/premium_features/test_util.clj b/test/metabase/premium_features/test_util.cljindex 8a8c22d25c7..06ed3274958 100644--- a/test/metabase/premium_features/test_util.clj+++ b/test/metabase/premium_features/test_util.clj@@ -21,6 +21,9 @@(thunk)))](if tu.thread-local/*thread-local*(thunk)+ ;; global mode — must use with-redefs so Jetty handler threads (which don't inherit *local-redefs*)+ ;; see the updated premium features.+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}(with-redefs [token-check/*token-features* (constantly features)](thunk)))))))diff --git a/test/metabase/premium_features/token_check_test.clj b/test/metabase/premium_features/token_check_test.cljindex 82ccbe329b3..41c84df79b0 100644--- a/test/metabase/premium_features/token_check_test.clj+++ b/test/metabase/premium_features/token_check_test.clj@@ -54,11 +54,11 @@(token-check/make-checker {:local-ttl (t/seconds 5):soft-ttl (t/minutes 1):hard-ttl (t/minutes 2)}))]- (with-redefs [token-check/http-fetch (fn [& _]- (swap! call-count inc)- (case @response- :error (throw (ex-info "kaboom" {:ka :boom}))- :500 {:status 500}))]+ (mt/with-dynamic-fn-redefs [token-check/http-fetch (fn [& _]+ (swap! call-count inc)+ (case @response+ :error (throw (ex-info "kaboom" {:ka :boom}))+ :500 {:status 500}))](testing "For timeouts, 5XX errors, etc. we don't cache the result"(dotimes [_ 5] (token-check/check-token checker token))(is (= 5 @call-count)))@@ -144,7 +144,7 @@:local-ttl (t/millis 50):soft-ttl (t/millis 200):hard-ttl (t/seconds 1)})]- (with-redefs [mdb/db-is-set-up? (constantly false)]+ (mt/with-dynamic-fn-redefs [mdb/db-is-set-up? (constantly false)](is (= {:valid false:canonical? false:status "Unable to validate token"@@ -157,7 +157,7 @@:error-details "Metabase DB is not yet set up"}(token-check/-check-token checker token))))(testing "When the db-is-set-up? we are not blocked by the circuit breaker"- (with-redefs [mdb/db-is-set-up? (constantly true)]+ (mt/with-dynamic-fn-redefs [mdb/db-is-set-up? (constantly true)](is (= good-response (token-check/-check-token checker token))))))))(defn- age-cache-entry!@@ -186,14 +186,14 @@:hard-ttl (t/hours 36):db-hash-local-cache local-cache}))](try- (with-redefs [token-check/http-fetch (fn [& _]- (swap! call-count inc)- {:status 200 :body good-body})]+ (mt/with-dynamic-fn-redefs [token-check/http-fetch (fn [& _]+ (swap! call-count inc)+ {:status 200 :body good-body})](is (= good-resp (token-check/check-token checker token)))(is (= 1 @call-count)))- (with-redefs [token-check/http-fetch (fn [& _]- (swap! call-count inc)- (throw (ex-info "network failure!" {})))]+ (mt/with-dynamic-fn-redefs [token-check/http-fetch (fn [& _]+ (swap! call-count inc)+ (throw (ex-info "network failure!" {})))](testing "Doesn't hit the network inside of cache duration";; Wait for local-cached-token-checker TTL to expire, but DB-hash-aware cache is still fresh(Thread/sleep 60)@@ -250,8 +250,8 @@:hard-ttl (t/hours 36):db-hash-local-cache local-cache}))](try- (with-redefs [token-check/http-fetch- (fn [& _] {:status 200 :body (json/encode @response)})]+ (mt/with-dynamic-fn-redefs [token-check/http-fetch+ (fn [& _] {:status 200 :body (json/encode @response)})](testing "successful response with :meters writes through"(reset! response {:valid true :status "ok":meters {:transform-basic-runs {:is-locked true}@@ -292,8 +292,8 @@:hard-ttl (t/hours 36):db-hash-local-cache local-cache}))](try- (with-redefs [token-check/http-fetch- (fn [& _] (throw (ex-info "network failure!" {})))]+ (mt/with-dynamic-fn-redefs [token-check/http-fetch+ (fn [& _] (throw (ex-info "network failure!" {})))](token-check/check-token checker token)(is (= {:transform-basic-runs true}(premium-features/locked-meters))@@ -332,46 +332,46 @@(deftest assert-valid-airgap-user-count-test(testing "no limit set - no error"- (with-redefs [token-check/max-users-allowed (constantly nil)]+ (mt/with-dynamic-fn-redefs [token-check/max-users-allowed (constantly nil)](is (nil? (token-check/assert-valid-airgap-user-count!)))))(testing "under limit - no error"- (with-redefs [token-check/max-users-allowed (constantly 10)- token-check/active-user-count (constantly 5)]+ (mt/with-dynamic-fn-redefs [token-check/max-users-allowed (constantly 10)+ token-check/active-user-count (constantly 5)](is (nil? (token-check/assert-valid-airgap-user-count!)))))(testing "at limit - no error"- (with-redefs [token-check/max-users-allowed (constantly 10)- token-check/active-user-count (constantly 10)]+ (mt/with-dynamic-fn-redefs [token-check/max-users-allowed (constantly 10)+ token-check/active-user-count (constantly 10)](is (nil? (token-check/assert-valid-airgap-user-count!)))))(testing "over limit - throws"- (with-redefs [token-check/max-users-allowed (constantly 10)- token-check/active-user-count (constantly 11)]+ (mt/with-dynamic-fn-redefs [token-check/max-users-allowed (constantly 10)+ token-check/active-user-count (constantly 11)](is (thrown-with-msg? Exception#"You have reached the maximum number of users"(token-check/assert-valid-airgap-user-count!))))))(deftest assert-airgap-allows-user-creation-test(testing "no limit set - no error"- (with-redefs [token-check/max-users-allowed (constantly nil)]+ (mt/with-dynamic-fn-redefs [token-check/max-users-allowed (constantly nil)](is (nil? (token-check/assert-airgap-allows-user-creation!)))))(testing "under limit - no error (room for one more)"- (with-redefs [token-check/max-users-allowed (constantly 10)- token-check/active-user-count (constantly 9)]+ (mt/with-dynamic-fn-redefs [token-check/max-users-allowed (constantly 10)+ token-check/active-user-count (constantly 9)](is (nil? (token-check/assert-airgap-allows-user-creation!)))))(testing "at limit - throws (no room for another)"- (with-redefs [token-check/max-users-allowed (constantly 10)- token-check/active-user-count (constantly 10)]+ (mt/with-dynamic-fn-redefs [token-check/max-users-allowed (constantly 10)+ token-check/active-user-count (constantly 10)](is (thrown-with-msg? Exception#"Adding another user would exceed the maximum"(token-check/assert-airgap-allows-user-creation!)))))(testing "over limit - throws"- (with-redefs [token-check/max-users-allowed (constantly 10)- token-check/active-user-count (constantly 11)]+ (mt/with-dynamic-fn-redefs [token-check/max-users-allowed (constantly 10)+ token-check/active-user-count (constantly 11)](is (thrown-with-msg? Exception#"Adding another user would exceed the maximum"(token-check/assert-airgap-allows-user-creation!))))))@@ -380,9 +380,9 @@(testing "send-metering-events! makes a POST request with correct data"(let [request-data (atom nil)](mt/with-random-premium-token! [_token]- (with-redefs [http/post (fn [url opts]- (reset! request-data {:url url :opts opts})- {:status 200 :body "{}"})]+ (mt/with-dynamic-fn-redefs [http/post (fn [url opts]+ (reset! request-data {:url url :opts opts})+ {:status 200 :body "{}"})](token-check/send-metering-events!)(is (some? @request-data) "POST request should have been made")(when @request-data@@ -406,15 +406,15 @@"openai:gpt-4:tokens" 300}request-data (atom nil)](mt/with-random-premium-token! [_token]- (with-redefs [token-check/metering-stats (constantly {:users 10- :external-users 2- :internal-users 8- :domains 1- :metabot-usage fake-usage- :metabot-tokens 800})- http/post (fn [_url opts]- (reset! request-data opts)- {:status 200 :body "{}"})]+ (mt/with-dynamic-fn-redefs [token-check/metering-stats (constantly {:users 10+ :external-users 2+ :internal-users 8+ :domains 1+ :metabot-usage fake-usage+ :metabot-tokens 800})+ http/post (fn [_url opts]+ (reset! request-data opts)+ {:status 200 :body "{}"})](token-check/send-metering-events!)(let [body (json/decode (:body @request-data) keyword)](is (= 10 (:users body))@@ -428,7 +428,7 @@(deftest send-metering-events-error-handling-test(testing "send-metering-events! handles errors gracefully"(mt/with-random-premium-token! [_token]- (with-redefs [http.core/request (fn [& _] (throw (Exception. "Network error")))]+ (mt/with-dynamic-fn-redefs [http.core/request (fn [& _] (throw (Exception. "Network error")))];; Should not throw, just log the error(is (nil? (token-check/send-metering-events!)))))))@@ -436,9 +436,9 @@(testing "send-metering-events! does nothing when no token is set"(let [request-made (atom false)](mt/with-temporary-setting-values [premium-embedding-token nil]- (with-redefs [http/post (fn [_url _opts]- (reset! request-made true)- {:status 200 :body "{}"})]+ (mt/with-dynamic-fn-redefs [http/post (fn [_url _opts]+ (reset! request-made true)+ {:status 200 :body "{}"})](token-check/send-metering-events!)(is (false? @request-made) "No request should be made without a token"))))))@@ -447,15 +447,15 @@(let [;; This is a fake airgap token format (starts with "airgap_")airgap-token "airgap_eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ90faketoken"request-made (atom false)]- (with-redefs [token-check/check-token- (constantly {:valid true- :status "fake"- :features ["test" "fixture"]- :trial false})]+ (mt/with-dynamic-fn-redefs [token-check/check-token+ (constantly {:valid true+ :status "fake"+ :features ["test" "fixture"]+ :trial false})](mt/with-temporary-raw-setting-values [premium-embedding-token airgap-token]- (with-redefs [http/post (fn [_url _opts]- (reset! request-made true)- {:status 200 :body "{}"})]+ (mt/with-dynamic-fn-redefs [http/post (fn [_url _opts]+ (reset! request-made true)+ {:status 200 :body "{}"})](token-check/send-metering-events!)(is (false? @request-made) "No request should be made for airgap tokens")))))))@@ -746,10 +746,10 @@(deftest set-premium-embedding-token-canonical-invalid-test(testing "When MetaStore says the token is invalid (canonical), throws 400 with MetaStore's message"(let [token (tu/random-token)]- (with-redefs [token-check/check-token (constantly {:valid false- :status "Token expired"- :error-details "Expired 2024-01-01"- :canonical? true})]+ (mt/with-dynamic-fn-redefs [token-check/check-token (constantly {:valid false+ :status "Token expired"+ :error-details "Expired 2024-01-01"+ :canonical? true})](let [e (try (token-check/-set-premium-embedding-token! token)nil(catch Exception e e))]@@ -761,9 +761,9 @@(deftest set-premium-embedding-token-non-canonical-failure-test(testing "When token validation fails for non-canonical reasons (network etc), throws 503"(let [token (tu/random-token)]- (with-redefs [token-check/check-token (constantly {:valid false- :status "Unable to validate token"- :error-details "Connection refused"})]+ (mt/with-dynamic-fn-redefs [token-check/check-token (constantly {:valid false+ :status "Unable to validate token"+ :error-details "Connection refused"})](let [e (try (token-check/-set-premium-embedding-token! token)nil(catch Exception e e))]@@ -775,9 +775,9 @@(deftest set-premium-embedding-token-valid-test(testing "When token is valid, no exception is thrown and setting is persisted"(let [token (tu/random-token)]- (with-redefs [token-check/check-token (constantly {:valid true- :status "OK"- :features ["test"]})]+ (mt/with-dynamic-fn-redefs [token-check/check-token (constantly {:valid true+ :status "OK"+ :features ["test"]})](mt/with-temporary-setting-values [premium-embedding-token nil](token-check/-set-premium-embedding-token! token)(is (= token (premium-features/premium-embedding-token))))))))diff --git a/test/metabase/product_feedback/api_test.clj b/test/metabase/product_feedback/api_test.cljindex b763b547cf4..95ad24ffafb 100644--- a/test/metabase/product_feedback/api_test.clj+++ b/test/metabase/product_feedback/api_test.clj@@ -18,10 +18,10 @@(deftest product-feedback-test-2(testing "fires the proxy in background"(let [sent? (promise)]- (with-redefs [product-feedback.api/send-feedback! (fn [comments source email]- (doseq [prop [comments source email]]- (is (not (str/blank? prop)) "got a blank property to send-feedback!"))- (deliver sent? true))]+ (mt/with-dynamic-fn-redefs [product-feedback.api/send-feedback! (fn [comments source email]+ (doseq [prop [comments source email]]+ (is (not (str/blank? prop)) "got a blank property to send-feedback!"))+ (deliver sent? true))](mt/user-http-request :crowberto :post 204 "product-feedback/"{:comments "I like Metabase":email "[email protected]"diff --git a/test/metabase/product_feedback/task/creator_sentiment_emails_test.clj b/test/metabase/product_feedback/task/creator_sentiment_emails_test.cljindex 6b93d9ceaea..579ffea1356 100644--- a/test/metabase/product_feedback/task/creator_sentiment_emails_test.clj+++ b/test/metabase/product_feedback/task/creator_sentiment_emails_test.clj@@ -16,9 +16,9 @@(doseq [enabled? [true false]](mt/reset-inbox!)(mt/with-temporary-setting-values [surveys-enabled enabled?]- (with-redefs [creator-sentiment-emails/fetch-creators (fn [_] [{:email "[email protected]"} ;; mods to 45, this email would be sent if surveys-enabled was true- {:email "[email protected]"} ;; mods to 4- {:email "[email protected]"}])] ;; mods to 26+ (mt/with-dynamic-fn-redefs [creator-sentiment-emails/fetch-creators (fn [_] [{:email "[email protected]"} ;; mods to 45, this email would be sent if surveys-enabled was true+ {:email "[email protected]"} ;; mods to 4+ {:email "[email protected]"}])] ;; mods to 26(#'creator-sentiment-emails/send-creator-sentiment-emails! 45)(is (= (if enabled? 1 0)@@ -29,9 +29,9 @@(mt/with-fake-inbox(mt/with-temporary-setting-values [surveys-enabled true](testing "Make sure that send-creator-sentiment-emails! only sends emails to creators with the correct week hash."- (with-redefs [creator-sentiment-emails/fetch-creators (fn [_] [{:email "[email protected]"} ;; mods to 45- {:email "[email protected]"} ;; mods to 4- {:email "[email protected]"}])] ;; mods to 26+ (mt/with-dynamic-fn-redefs [creator-sentiment-emails/fetch-creators (fn [_] [{:email "[email protected]"} ;; mods to 45+ {:email "[email protected]"} ;; mods to 4+ {:email "[email protected]"}])] ;; mods to 26(#'creator-sentiment-emails/send-creator-sentiment-emails! 45)(is (= 1@@ -43,11 +43,11 @@(doseq [tracking-enabled? [true false]](mt/reset-inbox!)(mt/with-temporary-setting-values [anon-tracking-enabled tracking-enabled?]- (with-redefs [creator-sentiment-emails/fetch-creators (fn [_] [{:email "[email protected]"- :created_at (t/local-date-time)- :num_dashboards 4- :num_questions 7- :num_models 2}])]+ (mt/with-dynamic-fn-redefs [creator-sentiment-emails/fetch-creators (fn [_] [{:email "[email protected]"+ :created_at (t/local-date-time)+ :num_dashboards 4+ :num_questions 7+ :num_models 2}])](#'creator-sentiment-emails/send-creator-sentiment-emails! 45)(is (= (if tracking-enabled? 1 0)(count (et/regex-email-bodies #"creator\?context="))))@@ -75,9 +75,9 @@(testing "Make sure external services message is included when is self hosted"(doseq [hosted? [true false]](mt/reset-inbox!)- (with-redefs [creator-sentiment-emails/fetch-creators (fn [_] [{:email "[email protected]"}])+ (mt/with-dynamic-fn-redefs [creator-sentiment-emails/fetch-creators (fn [_] [{:email "[email protected]"}]);; can't use mt/with-temporary-setting-values because of a custom :getter- premium-features/is-hosted? (constantly hosted?)]+ premium-features/is-hosted? (constantly hosted?)](mt/with-temporary-setting-values [site-url "http://metabase.com"](#'creator-sentiment-emails/send-creator-sentiment-emails! 45)(is (= (if hosted? 0 1)diff --git a/test/metabase/pulse/api/pulse_test.clj b/test/metabase/pulse/api/pulse_test.cljindex 1d534abcb74..f063ae5ccda 100644--- a/test/metabase/pulse/api/pulse_test.clj+++ b/test/metabase/pulse/api/pulse_test.clj@@ -1130,8 +1130,8 @@(deftest send-test-pulse-validate-emails-test(testing (str "POST /api/pulse/test should call " `pulse-channel/validate-email-domains)(mt/with-temp [:model/Card card {:dataset_query (mt/mbql-query venues)}]- (with-redefs [pulse-channel/validate-email-domains (fn [& _]- (throw (ex-info "Nope!" {:status-code 403})))]+ (mt/with-dynamic-fn-redefs [pulse-channel/validate-email-domains (fn [& _]+ (throw (ex-info "Nope!" {:status-code 403})))];; make sure we validate raw emails whether they're part of `:details` or part of `:recipients` -- we;; technically allow either right now(doseq [channel [{:details {:emails ["[email protected]"]}}diff --git a/test/metabase/pulse/pulse_integration_test.clj b/test/metabase/pulse/pulse_integration_test.cljindex 22d108401ad..5540f275286 100644--- a/test/metabase/pulse/pulse_integration_test.clj+++ b/test/metabase/pulse/pulse_integration_test.clj@@ -65,7 +65,7 @@element. In our test cases that's the Tax Rate column."[pulse](let [channel-messages (pulse.test-util/with-captured-channel-send-messages!- (with-redefs [channel.settings/bcc-enabled? (constantly false)]+ (mt/with-dynamic-fn-redefs [channel.settings/bcc-enabled? (constantly false)](mt/with-test-user nil(pulse.send/send-pulse! pulse))))html-body (-> channel-messages :channel/email first :message first :content)@@ -189,7 +189,7 @@"Simulate sending the pulse email, get the attached text/csv content, and parse into a map ofattachment name -> column name -> column data"[pulse]- (with-redefs [channel.settings/bcc-enabled? (constantly false)]+ (mt/with-dynamic-fn-redefs [channel.settings/bcc-enabled? (constantly false)](->> (mt/with-test-user nil(pulse.test-util/with-captured-channel-send-messages!(pulse.send/send-pulse! pulse)))@@ -612,7 +612,7 @@:model/PulseChannelRecipient _ {:pulse_channel_id pulse-channel-id:user_id (mt/user->id :rasta)}](let [attachment-name->cols (mt/with-fake-inbox- (with-redefs [channel.settings/bcc-enabled? (constantly false)]+ (mt/with-dynamic-fn-redefs [channel.settings/bcc-enabled? (constantly false)](mt/with-test-user nil(pulse.send/send-pulse! pulse)))(->>@@ -642,7 +642,7 @@"Simulate sending the pulse email, get the html body of the response and return the scalar value of the card."[pulse](mt/with-fake-inbox- (with-redefs [channel.settings/bcc-enabled? (constantly false)]+ (mt/with-dynamic-fn-redefs [channel.settings/bcc-enabled? (constantly false)](mt/with-test-user nil(pulse.send/send-pulse! pulse)))(let [html-body (get-in @mt/inbox ["[email protected]" 0 :body 0 :content])@@ -704,7 +704,7 @@If not pulse is sent, return `nil`."[pulse](mt/with-fake-inbox- (with-redefs [channel.settings/bcc-enabled? (constantly false)]+ (mt/with-dynamic-fn-redefs [channel.settings/bcc-enabled? (constantly false)](mt/with-test-user nil(pulse.send/send-pulse! pulse)))(when-some [html-body (get-in @mt/inbox ["[email protected]" 0 :body 0 :content])]@@ -855,7 +855,7 @@:model/PulseChannelRecipient _ {:pulse_channel_id pulse-channel-id:user_id (mt/user->id :rasta)}](mt/with-fake-inbox- (with-redefs [channel.settings/bcc-enabled? (constantly false)]+ (mt/with-dynamic-fn-redefs [channel.settings/bcc-enabled? (constantly false)](mt/with-test-user nil(pulse.send/send-pulse! pulse)))(let [html-body (get-in @mt/inbox ["[email protected]" 0 :body 0 :content])@@ -890,7 +890,7 @@:model/PulseChannelRecipient _ {:pulse_channel_id pulse-channel-id:user_id (mt/user->id :rasta)}](mt/with-fake-inbox- (with-redefs [channel.settings/bcc-enabled? (constantly false)]+ (mt/with-dynamic-fn-redefs [channel.settings/bcc-enabled? (constantly false)](mt/with-test-user nil(pulse.send/send-pulse! pulse)))(let [html-body (get-in @mt/inbox ["[email protected]" 0 :body 0 :content])]@@ -967,7 +967,7 @@:model/PulseChannelRecipient _ {:pulse_channel_id pulse-channel-id:user_id (mt/user->id :rasta)}](mt/with-fake-inbox- (with-redefs [channel.settings/bcc-enabled? (constantly false)]+ (mt/with-dynamic-fn-redefs [channel.settings/bcc-enabled? (constantly false)](mt/with-test-user nil(pulse.send/send-pulse! pulse)))(is (string? (get-in @mt/inbox ["[email protected]" 0 :body 0 :content])))))))))diff --git a/test/metabase/pulse/send_test.clj b/test/metabase/pulse/send_test.cljindex cc7a3772000..36a8eb69f24 100644--- a/test/metabase/pulse/send_test.clj+++ b/test/metabase/pulse/send_test.clj@@ -636,7 +636,7 @@:model/PulseChannel _ {:pulse_id pulse-id:channel_type "slack":details {:channel "#general"}}]- (let [original-render-noti (var-get #'channel/render-notification)]+ (let [original-render-noti (mt/original-fn #'channel/render-notification)](with-redefs [channel/render-notification (fn [& args](if (= :channel/slack (first args))(throw (ex-info "Slack failed" {}))@@ -703,7 +703,7 @@(deftest send-skip-alert-test(testing "alerts are skipped (#63189)"(let [pulse-sent-called? (atom false)]- (with-redefs [pulse.send/send-pulse!* (fn [& _args])]+ (mt/with-dynamic-fn-redefs [pulse.send/send-pulse!* (fn [& _args])](mt/with-temp [:model/Pulse {pulse-id :id:as pulse} {:creator_id (mt/user->id :rasta):name (mt/random-name)diff --git a/test/metabase/pulse/task/send_pulses_test.clj b/test/metabase/pulse/task/send_pulses_test.cljindex c3b3f54eaeb..1bb767306df 100644--- a/test/metabase/pulse/task/send_pulses_test.clj+++ b/test/metabase/pulse/task/send_pulses_test.clj@@ -110,8 +110,8 @@(deftest send-pulse!*-delete-pcs-no-recipients-test(testing "send-pulse!* should delete PulseChannels and only send to enabled channels"(let [sent-channel-ids (atom #{})]- (with-redefs [pulse.send/send-pulse! (fn [_pulse-id & {:keys [channel-ids]}]- (swap! sent-channel-ids set/union channel-ids))]+ (mt/with-dynamic-fn-redefs [pulse.send/send-pulse! (fn [_pulse-id & {:keys [channel-ids]}]+ (swap! sent-channel-ids set/union channel-ids))](mt/with-temp[:model/Pulse {pulse :id} {}:model/PulseChannel {pc :id} (merge@@ -212,8 +212,11 @@(pulse-channel-test/with-send-pulse-setup!(mt/with-model-cleanup [:model/Pulse](let [sent-channel-ids (atom #{})]+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}(with-redefs [;; run the job every secondu.cron/schedule-map->cron-string (constantly "* * * 1/1 * ? *")+ ;; quartz scheduler threads don't inherit *local-redefs*, so we have to swap the+ ;; root — see dynamic-redefs.clj docstringtask.send-pulses/send-pulse! (fn [_pulse-id channel-ids](swap! sent-channel-ids set/union channel-ids))](let [pc-count (+ 2 mt.util/in-memory-scheduler-thread-count)@@ -243,7 +246,10 @@(notification.tu/with-captured-channel-send!(let [sent-pulse-ids (atom #{})send-pulse-called (atom 0)- original-send-pulse!* @#'task.send-pulses/send-pulse!*]+ original-send-pulse!* (mt/original-fn #'task.send-pulses/send-pulse!*)]+ ;; quartz scheduler threads don't inherit *local-redefs*, so we have to swap the+ ;; root — see dynamic-redefs.clj docstring+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}(with-redefs [;; run the job every second - must be before creating PulseChannelu.cron/schedule-map->cron-string (constantly "* * * 1/1 * ? *")task.send-pulses/send-pulse!* (fn [pulse-id channel-ids]diff --git a/test/metabase/queries/models/card_test.clj b/test/metabase/queries/models/card_test.cljindex bcad7b0398a..1044b359013 100644--- a/test/metabase/queries/models/card_test.clj+++ b/test/metabase/queries/models/card_test.clj@@ -157,8 +157,8 @@(testing "should not attempt to delete if it's not a model"(mt/with-temp [:model/Card {id :id} {:type :question:dataset_query (mt/mbql-query users)}]- (with-redefs [card/disable-implicit-action-for-model! (fn [& _args]- (throw (ex-info "Should not be called" {})))]+ (mt/with-dynamic-fn-redefs [card/disable-implicit-action-for-model! (fn [& _args]+ (throw (ex-info "Should not be called" {})))](is (= 1 (t2/update! :model/Card :id id {:dataset_query (mt/mbql-query users {:limit 1})})))))))))(deftest disable-implicit-actions-if-needed-test-3@@ -969,7 +969,7 @@(mt/with-premium-features #{}(mt/with-temp [:model/Collection collection {}:model/Card card {:collection_id (:id collection)}]- (with-redefs [audit/default-audit-collection (constantly collection)]+ (mt/with-dynamic-fn-redefs [audit/default-audit-collection (constantly collection)](mt/with-test-user :rasta(is (false? (mi/can-read? card)))(is (false? (mi/can-write? card))))diff --git a/test/metabase/queries_rest/api/card_test.clj b/test/metabase/queries_rest/api/card_test.cljindex 5044d787c6d..611260baf20 100644--- a/test/metabase/queries_rest/api/card_test.clj+++ b/test/metabase/queries_rest/api/card_test.clj@@ -1069,11 +1069,11 @@(deftest updating-card-updates-metadata-2(let [query (updating-card-updates-metadata-query)](testing "Updating other parts but not query does not update the metadata"- (let [orig @#'card.metadata/legacy-result-metadata-future+ (let [orig (mt/original-fn #'card.metadata/legacy-result-metadata-future)called (atom 0)]- (with-redefs [card.metadata/legacy-result-metadata-future (fn [q]- (swap! called inc)- (orig q))]+ (mt/with-dynamic-fn-redefs [card.metadata/legacy-result-metadata-future (fn [q]+ (swap! called inc)+ (orig q))](mt/with-model-cleanup [:model/Card](let [card (mt/user-http-request :crowberto :post 200 "card"(card-with-name-and-query "card-name"@@ -2656,16 +2656,16 @@:middleware {:add-default-userland-constraints? true:userland-query? true}}}](with-cards-in-readable-collection! card- (let [orig qp.card/process-query-for-card]- (with-redefs [qp.card/process-query-for-card (fn [card-id export-format & options]- (apply orig card-id export-format- :make-run (constantly (fn [{:keys [constraints]} _]- {:constraints constraints}))- options))]+ (let [orig (mt/original-fn #'qp.card/process-query-for-card)]+ (mt/with-dynamic-fn-redefs [qp.card/process-query-for-card (fn [card-id export-format & options]+ (apply orig card-id export-format+ :make-run (constantly (fn [{:keys [constraints]} _]+ {:constraints constraints}))+ options))](testing "Sanity check: this CSV download should not be subject to C O N S T R A I N T S"(is (= {:constraints nil}(mt/user-http-request :rasta :post 200 (format "card/%d/query/csv" (u/the-id card))))))- (with-redefs [qp.constraints/default-query-constraints (constantly {:max-results 10, :max-results-bare-rows 10})]+ (mt/with-dynamic-fn-redefs [qp.constraints/default-query-constraints (constantly {:max-results 10, :max-results-bare-rows 10})](testing (str "Downloading CSV/JSON/XLSX results shouldn't be subject to the default query constraints -- even ""if the query comes in with `add-default-userland-constraints` (as will be the case if the query ""gets saved from one that had it -- see #9831)")@@ -3445,7 +3445,7 @@(testing "fallback to field-values"(let [mock-default-result {:values [["field-values"]]:has_more_values false}]- (with-redefs [queries.card/mapping->field-values (constantly mock-default-result)]+ (mt/with-dynamic-fn-redefs [queries.card/mapping->field-values (constantly mock-default-result)](testing "if value-field not found in source card"(mt/with-temp[:model/Card {source-card-id :id} {}diff --git a/test/metabase/query_processor/api_test.clj b/test/metabase/query_processor/api_test.cljindex c84af458a5d..065131b5842 100644--- a/test/metabase/query_processor/api_test.clj+++ b/test/metabase/query_processor/api_test.clj@@ -260,9 +260,9 @@(some #(str/includes? % long-col-name) native-form-lines)));; Disable truncate-alias when compiling the native query to ensure we don't truncate the column.;; We want to simulate a user-defined query where the column name is long, but valid for the driver.- native-sub-query (with-redefs [metabase.lib.util.unique-name-generator/truncate-alias- (fn mock-truncate-alias- [ss & _] ss)]+ native-sub-query (mt/with-dynamic-fn-redefs [metabase.lib.util.unique-name-generator/truncate-alias+ (fn mock-truncate-alias+ [ss & _] ss)];; make sure the schema checks don't fail for aliases > 60 characters(mu/disable-enforcement(-> (mt/mbql-query people@@ -320,7 +320,7 @@(testing "POST /api/dataset/:format"(testing "Downloading CSV/JSON/XLSX results shouldn't be subject to the default query constraints (#9831)";; even if the query comes in with `add-default-userland-constraints` (as will be the case if the query gets saved- (with-redefs [qp.constraints/default-query-constraints (constantly {:max-results 10, :max-results-bare-rows 10})]+ (mt/with-dynamic-fn-redefs [qp.constraints/default-query-constraints (constantly {:max-results 10, :max-results-bare-rows 10})](doseq [:let [query {:database (mt/id):type :query:query {:source-table (mt/id :venues)}@@ -369,7 +369,7 @@(deftest non-download-queries-should-still-get-the-default-constraints(testing (str "non-\"download\" queries should still get the default constraints ""(this also is a sanitiy check to make sure the `with-redefs` in the test above actually works)")- (with-redefs [qp.constraints/default-query-constraints (constantly {:max-results 10, :max-results-bare-rows 10})]+ (mt/with-dynamic-fn-redefs [qp.constraints/default-query-constraints (constantly {:max-results 10, :max-results-bare-rows 10})](let [{row-count :row_count, :as result}(mt/user-http-request :crowberto :post 202 "dataset"{:database (mt/id)@@ -906,7 +906,7 @@(testing "fallback to field-values"(let [mock-default-result {:values [["field-values"]]:has_more_values false}]- (with-redefs [api.dataset/parameter-field-values (constantly mock-default-result)]+ (mt/with-dynamic-fn-redefs [api.dataset/parameter-field-values (constantly mock-default-result)](testing "if value-field not found in source card"(mt/with-temp [:model/Card {source-card-id :id}](is (= mock-default-result@@ -1031,7 +1031,7 @@(deftest pivot-exports-ignore-query-constraints(testing "POST /api/dataset/:format with pivot-results=true"(testing "Downloading pivot CSV/JSON/XLSX results shouldn't be subject to the default query constraints"- (with-redefs [qp.constraints/default-query-constraints (constantly {:max-results 10, :max-results-bare-rows 10})]+ (mt/with-dynamic-fn-redefs [qp.constraints/default-query-constraints (constantly {:max-results 10, :max-results-bare-rows 10})](let [query {:database (mt/id):type :query:query {:source-table (mt/id :venues)diff --git a/test/metabase/query_processor/middleware/cache_test.clj b/test/metabase/query_processor/middleware/cache_test.cljindex 99ef9e666d7..7d15160e640 100644--- a/test/metabase/query_processor/middleware/cache_test.clj+++ b/test/metabase/query_processor/middleware/cache_test.clj@@ -108,16 +108,16 @@(binding [cache/*backend* (test-backend save-chan purge-chan)*save-chan* save-chan*purge-chan* purge-chan]- (let [orig @#'cache/serialized-bytes]- (with-redefs [cache/serialized-bytes (fn []+ (let [orig (mt/original-fn #'cache/serialized-bytes)]+ (mt/with-dynamic-fn-redefs [cache/serialized-bytes (fn [];; if `save-results!` isn't going to get called because `*result-fn*`;; throws an Exception, catch it and send it to `save-chan` so it still;; gets a result and tests can finish- (try- (orig)- (catch Throwable e- (a/>!! save-chan e)- (throw e))))]+ (try+ (orig)+ (catch Throwable e+ (a/>!! save-chan e)+ (throw e))))](f {:save-chan save-chan, :purge-chan purge-chan})))))))(defmacro with-mock-cache! [[& bindings] & body]@@ -420,8 +420,11 @@(let [save-execution-metadata-count (atom 0)update-avg-execution-count (atom 0)called-promise (promise)- save-execution-metadata-original (var-get #'process-userland-query/save-execution-metadata!*)- save-query-update-avg-time-original query/save-query-and-update-average-execution-time!]+ save-execution-metadata-original (mt/original-fn #'process-userland-query/save-execution-metadata!*)+ save-query-update-avg-time-original (mt/original-fn #'query/save-query-and-update-average-execution-time!)]+ ;; save-execution-metadata!* and save-query-and-update-average-execution-time! are invoked from+ ;; the QP pipeline on worker threads that don't inherit *local-redefs* — use with-redefs.+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}(with-redefs [process-userland-query/save-execution-metadata!* (fn [& args](swap! save-execution-metadata-count inc)(apply save-execution-metadata-original args)@@ -662,8 +665,8 @@(fn [rff](qp/process-query (dissoc query :cache-strategy) rff)))(vec (csv/read-csv reader)))]- (with-redefs [sql-jdbc.execute/execute-reducible-query (fn [& _]- (throw (Exception. "Should be cached!")))]+ (mt/with-dynamic-fn-redefs [sql-jdbc.execute/execute-reducible-query (fn [& _]+ (throw (Exception. "Should be cached!")))](with-open [ostream (java.io.PipedOutputStream.)istream (java.io.PipedInputStream. ostream)reader (java.io.InputStreamReader. istream)]diff --git a/test/metabase/query_processor/middleware/catch_exceptions_test.clj b/test/metabase/query_processor/middleware/catch_exceptions_test.cljindex b2316b0e234..b7ab8a320dc 100644--- a/test/metabase/query_processor/middleware/catch_exceptions_test.clj+++ b/test/metabase/query_processor/middleware/catch_exceptions_test.clj@@ -109,8 +109,8 @@(testing "compile and preprocess should not be called if no exception occurs"(let [compile-call-count (atom 0)preprocess-call-count (atom 0)]- (with-redefs [qp.compile/compile (fn [_] (swap! compile-call-count inc))- qp.preprocess/preprocess (fn [_] (swap! preprocess-call-count inc))]+ (mt/with-dynamic-fn-redefs [qp.compile/compile (fn [_] (swap! compile-call-count inc))+ qp.preprocess/preprocess (fn [_] (swap! preprocess-call-count inc))](is (= {:data {}, :row_count 0, :status :completed}(catch-exceptions (fn run []))))(is (= 0 @compile-call-count))diff --git a/test/metabase/query_processor/middleware/metrics_test.clj b/test/metabase/query_processor/middleware/metrics_test.cljindex c11be45b9c0..a74b06c86a9 100644--- a/test/metabase/query_processor/middleware/metrics_test.clj+++ b/test/metabase/query_processor/middleware/metrics_test.clj@@ -111,7 +111,7 @@:metabase-query-processor/metrics-adjust 1:metabase-query-processor/metrics-adjust-errors 1:check-fn (fn [query]- (with-redefs [metrics/adjust-metric-stages (fn [_ _ stages] stages)]+ (mt/with-dynamic-fn-redefs [metrics/adjust-metric-stages (fn [_ _ stages] stages)](try(adjust query)(is false "Failed to throw expected Exception")@@ -127,7 +127,7 @@:metabase-query-processor/metrics-adjust 1:metabase-query-processor/metrics-adjust-errors 1:check-fn (fn [query]- (with-redefs [lib.metadata/bulk-metadata-or-throw (fn [& _] (throw (Exception. "Test exception")))]+ (mt/with-dynamic-fn-redefs [lib.metadata/bulk-metadata-or-throw (fn [& _] (throw (Exception. "Test exception")))](is (thrown-with-msg?java.lang.Exception#"Test exception"diff --git a/test/metabase/query_processor/middleware/process_userland_query_test.clj b/test/metabase/query_processor/middleware/process_userland_query_test.cljindex 17f97712b2e..bac75b4799d 100644--- a/test/metabase/query_processor/middleware/process_userland_query_test.clj+++ b/test/metabase/query_processor/middleware/process_userland_query_test.clj@@ -26,6 +26,9 @@(mt/with-clock #t "2020-02-04T12:22-08:00[US/Pacific]"(let [original-hash (qp.util/query-hash query)result (promise)]+ ;; save-execution-metadata!* is invoked from the QP pipeline transducer, which runs on a thread+ ;; that doesn't inherit *local-redefs* — use with-redefs so worker threads see the replacement.+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}(with-redefs [process-userland-query/save-execution-metadata!*(fn [query-execution](when-let [^bytes qe-hash (:hash query-execution)]@@ -205,8 +208,8 @@(deftest cancel-test(let [saved-query-execution? (atom false)]- (with-redefs [process-userland-query/save-execution-metadata! (fn [info]- (reset! saved-query-execution? info))]+ (mt/with-dynamic-fn-redefs [process-userland-query/save-execution-metadata! (fn [info]+ (reset! saved-query-execution? info))](mt/with-open-channels [canceled-chan (a/promise-chan)](let [status (atom ::not-started)](binding [qp.pipeline/*canceled-chan* canceled-chandiff --git a/test/metabase/query_processor/middleware/results_metadata_test.clj b/test/metabase/query_processor/middleware/results_metadata_test.cljindex dccd0690204..76dfc3b2076 100644--- a/test/metabase/query_processor/middleware/results_metadata_test.clj+++ b/test/metabase/query_processor/middleware/results_metadata_test.clj@@ -194,11 +194,11 @@(middleware.results-metadata/store-previous-result-metadata!{:result_metadata cols-1})(let [call-count (atom 0)- t2-update!-orig t2/update!]- (with-redefs [t2/update! (fn [modelable & args]- (when (= :model/Card modelable)- (swap! call-count inc))- (apply t2-update!-orig modelable args))]+ t2-update!-orig (mt/original-fn #'t2/update!)]+ (mt/with-dynamic-fn-redefs [t2/update! (fn [modelable & args]+ (when (= :model/Card modelable)+ (swap! call-count inc))+ (apply t2-update!-orig modelable args))](let [result (qp/process-query(qp/userland-query(mt/native-query {:query "SELECT NAME FROM VENUES ORDER BY ID ASC LIMIT 5;"})diff --git a/test/metabase/query_processor/nested_queries_test.clj b/test/metabase/query_processor/nested_queries_test.cljindex 3a5f223fb90..99f94541c39 100644--- a/test/metabase/query_processor/nested_queries_test.clj+++ b/test/metabase/query_processor/nested_queries_test.clj@@ -368,10 +368,10 @@(count long-col-full-name)));; Disable truncate-alias when compiling the native query to ensure we don't further truncate the column.;; We want to simulate a user-defined query where the column name is long, but valid for the driver.- native-sub-query (with-redefs [metabase.lib.util.unique-name-generator/truncate-alias- (fn mock-truncate-alias- ([ss] ss)- ([ss _] ss))]+ native-sub-query (mt/with-dynamic-fn-redefs [metabase.lib.util.unique-name-generator/truncate-alias+ (fn mock-truncate-alias+ ([ss] ss)+ ([ss _] ss))](mu/disable-enforcement(-> (mt/mbql-query people{:source-table $$peoplediff --git a/test/metabase/query_processor/streaming_test.clj b/test/metabase/query_processor/streaming_test.cljindex 580d423f1d8..7efa708a032 100644--- a/test/metabase/query_processor/streaming_test.clj+++ b/test/metabase/query_processor/streaming_test.clj@@ -766,7 +766,7 @@(testing "Streaming response handles cancellation gracefully without assertion errors"(let [mock-qp-fn (fn [rff];; Simulate immediate cancellation- (with-redefs [qp.pipeline/canceled? (constantly true)]+ (mt/with-dynamic-fn-redefs [qp.pipeline/canceled? (constantly true)](qp.pipeline/*run* (mt/mbql-query venues {:limit 1}) rff)))];; Should not throw "QP unexpectedly returned nil" assertion error@@ -777,7 +777,7 @@(testing "Streaming response handles nil + canceled? gracefully"(let [mock-qp-fn (fn [_rff];; Return nil and set up canceled? to return truthy- (with-redefs [qp.pipeline/canceled? (constantly ::cancel)]+ (mt/with-dynamic-fn-redefs [qp.pipeline/canceled? (constantly ::cancel)]nil))];; Should not throw any assertion errorsdiff --git a/test/metabase/query_processor/util/relative_datetime_test.clj b/test/metabase/query_processor/util/relative_datetime_test.cljindex 9ab1853fc88..a934eda4d17 100644--- a/test/metabase/query_processor/util/relative_datetime_test.clj+++ b/test/metabase/query_processor/util/relative_datetime_test.clj@@ -25,7 +25,7 @@;; This was standard before PR #38604, now server side timestamps are used for that. This test confirms that;; server side generated timestamp (ie. new code path) results are equal to old code path results, that were not;; cacheable.- (let [honey {:select [[(with-redefs [qp.relative-datetime/use-server-side-relative-datetime? (constantly false)]+ (let [honey {:select [[(mt/with-dynamic-fn-redefs [qp.relative-datetime/use-server-side-relative-datetime? (constantly false)](sql.qp/->honeysql driver/*driver* [:relative-datetime value unit]))][(sql.qp/->honeysql driver/*driver* [:relative-datetime value unit])]]}sql (sql/format honey)diff --git a/test/metabase/request/util_test.clj b/test/metabase/request/util_test.cljindex f019d97b964..8b2f844ec6d 100644--- a/test/metabase/request/util_test.clj+++ b/test/metabase/request/util_test.clj@@ -194,6 +194,6 @@(is (= 1.0 (mt/metric-value system :metabase-geocoding/requests))))))(testing "increments :metabase-geocoding/errors on failed geocoding"(mt/with-prometheus-system! [_ system]- (with-redefs [http/get (fn [_ _] (throw (Exception. "Network error")))]+ (mt/with-dynamic-fn-redefs [http/get (fn [_ _] (throw (Exception. "Network error")))](req.util/geocode-ip-addresses ["8.8.8.8"])(is (= 1.0 (mt/metric-value system :metabase-geocoding/errors)))))))diff --git a/test/metabase/revisions/models/revision_test.clj b/test/metabase/revisions/models/revision_test.cljindex 5873545d019..9a5954cd0c2 100644--- a/test/metabase/revisions/models/revision_test.clj+++ b/test/metabase/revisions/models/revision_test.clj@@ -19,14 +19,14 @@(derive ::FakedCard :metabase/model)(defn- do-with-model-i18n-strs! [thunk]- (with-redefs [revision.diff/model-str->i18n-str (fn [model-str]- (case model-str- "Dashboard" (deferred-tru "Dashboard")- "Card" (deferred-tru "Card")- "Segment" (deferred-tru "Segment")- "Metric" (deferred-tru "Metric")- "NonExistModel" "NonExistModel"- "FakeCard" "FakeCard"))]+ (mt/with-dynamic-fn-redefs [revision.diff/model-str->i18n-str (fn [model-str]+ (case model-str+ "Dashboard" (deferred-tru "Dashboard")+ "Card" (deferred-tru "Card")+ "Segment" (deferred-tru "Segment")+ "Metric" (deferred-tru "Metric")+ "NonExistModel" "NonExistModel"+ "FakeCard" "FakeCard"))](thunk)))(defmethod revision/serialize-instance ::FakedCarddiff --git a/test/metabase/sample_data/impl_test.clj b/test/metabase/sample_data/impl_test.cljindex 51637a213a3..44b5ccf36b7 100644--- a/test/metabase/sample_data/impl_test.clj+++ b/test/metabase/sample_data/impl_test.clj@@ -55,15 +55,15 @@(deftest extract-sample-database-test(testing "The Sample Database is copied out of the JAR into the plugins directory before the DB details are saved."- (with-redefs [sync/sync-database! (constantly nil)]+ (mt/with-dynamic-fn-redefs [sync/sync-database! (constantly nil)](with-temp-sample-database-db [db](let [db-path (get-in db [:details :db])](is (re-matches extracted-db-path-regex db-path))))))(testing "If the plugins directory is not creatable or writable, we fall back to reading from the DB in the JAR"(memoize/memo-clear! @#'plugins/plugins-dir*)- (let [original-var u.files/create-dir-if-not-exists!]- (with-redefs [u.files/create-dir-if-not-exists! (fn [_] (throw (Exception.)))]+ (let [original-var (mt/original-fn #'u.files/create-dir-if-not-exists!)]+ (mt/with-dynamic-fn-redefs [u.files/create-dir-if-not-exists! (fn [_] (throw (Exception.)))](with-temp-sample-database-db [db](let [db-path (get-in db [:details :db])](is (not (str/includes? db-path "plugins"))))diff --git a/test/metabase/search/api_test.clj b/test/metabase/search/api_test.cljindex c72b882cced..f4708e1a596 100644--- a/test/metabase/search/api_test.clj+++ b/test/metabase/search/api_test.clj@@ -829,9 +829,9 @@(search! "rom" :rasta))))))(testing "Sandboxed users do not see indexed entities in search"- (with-redefs [perms-util/impersonated-user? (constantly true)]+ (mt/with-dynamic-fn-redefs [perms-util/impersonated-user? (constantly true)](is (empty? (into #{} (comp relevant-1 (map :name)) (search! "fort")))))- (with-redefs [perms-util/sandboxed-user? (constantly true)]+ (mt/with-dynamic-fn-redefs [perms-util/sandboxed-user? (constantly true)](is (empty? (into #{} (comp relevant-1 (map :name)) (search! "fort")))))))))))(defn- archived-collection [m]diff --git a/test/metabase/search/in_place/filter_test.clj b/test/metabase/search/in_place/filter_test.cljindex 3a174111ab5..adbaedc47b2 100644--- a/test/metabase/search/in_place/filter_test.clj+++ b/test/metabase/search/in_place/filter_test.clj@@ -403,7 +403,7 @@(deftest build-filters-indexed-entity-test(testing "users that are not sandboxed or impersonated can search for indexed entity"- (with-redefs [search.permissions/sandboxed-or-impersonated-user? (constantly false)]+ (mt/with-dynamic-fn-redefs [search.permissions/sandboxed-or-impersonated-user? (constantly false)](is (= [:and[:or [:like [:lower :model-index-value.name] "%foo%"]][:inline [:= 1 1]]]@@ -414,7 +414,7 @@(deftest build-filters-indexed-entity-test-2(testing "otherwise search result is empty"- (with-redefs [search.permissions/sandboxed-or-impersonated-user? (constantly true)]+ (mt/with-dynamic-fn-redefs [search.permissions/sandboxed-or-impersonated-user? (constantly true)](is (= [:and[:or [:= 0 1]][:inline [:= 1 1]]]diff --git a/test/metabase/search/in_place/scoring_test.clj b/test/metabase/search/in_place/scoring_test.cljindex 07f6183208f..2511e83a211 100644--- a/test/metabase/search/in_place/scoring_test.clj+++ b/test/metabase/search/in_place/scoring_test.clj@@ -294,10 +294,10 @@(deftest score-and-result-test(testing "If all scores are 0, does not divide by zero"- (with-redefs [scoring/score-result- (fn [_]- [{:weight 100 :score 0 :name "Some score type"}- {:weight 100 :score 0 :name "Some other score type"}])]+ (mt/with-dynamic-fn-redefs [scoring/score-result+ (fn [_]+ [{:weight 100 :score 0 :name "Some score type"}+ {:weight 100 :score 0 :name "Some other score type"}])](is (= 0 (:score (scoring/score-and-result {:name "racing yo" :model "card"}{:search-string "" :search-native-query nil})))))))diff --git a/test/metabase/server/instance_test.clj b/test/metabase/server/instance_test.cljindex 3aa1ed56ab6..f3007d6684e 100644--- a/test/metabase/server/instance_test.clj+++ b/test/metabase/server/instance_test.clj@@ -2,12 +2,13 @@(:require[clojure.test :refer :all][metabase.config.core :as config]- [metabase.server.instance :as server.instance]))+ [metabase.server.instance :as server.instance]+ [metabase.test :as mt]))(deftest config-test(testing "Make sure our Jetty config functions work as expected/we don't accidentally break things (#9333)"- (with-redefs [config/config-str (constantly "10")- config/config-bool (constantly true)]+ (mt/with-dynamic-fn-redefs [config/config-str (constantly "10")+ config/config-bool (constantly true)](is (= {:keystore "10":max-queued 10:request-header-size 10diff --git a/test/metabase/server/middleware/embedding_sdk_bundle_test.clj b/test/metabase/server/middleware/embedding_sdk_bundle_test.cljindex c7941fa6c17..3d3908c00de 100644--- a/test/metabase/server/middleware/embedding_sdk_bundle_test.clj+++ b/test/metabase/server/middleware/embedding_sdk_bundle_test.clj@@ -6,6 +6,7 @@[metabase.server.lib.etag-cache :as lib.etag-cache][metabase.server.middleware.embedding-sdk-bundle :as mw.embedding-sdk-bundle][metabase.server.routes.static :as static]+ [metabase.test :as mt][ring.util.response :as response]))(set! *warn-on-reflection* true)@@ -120,10 +121,10 @@(deftest serve-chunk-handler-returns-far-future-cache(testing "Chunk handler always returns far-future cache + Content-Type + Vary"- (with-redefs [static/static-resource (constantly {:status 200- :headers {"Content-Type" js-ct- "Vary" "Accept-Encoding"}- :body "chunk-js"})]+ (mt/with-dynamic-fn-redefs [static/static-resource (constantly {:status 200+ :headers {"Content-Type" js-ct+ "Vary" "Accept-Encoding"}+ :body "chunk-js"})](let [handler (mw.embedding-sdk-bundle/serve-chunk-handler "embedding-sdk-chunk-runtime.a1b2c3d4.js")resp (handler {:headers {}})](is (= 200 (:status resp)))@@ -132,7 +133,7 @@(is (= "Accept-Encoding" (get-in resp [:headers "Vary"]))))))(testing "Missing chunk resource → 404"- (with-redefs [static/static-resource (constantly nil)]+ (mt/with-dynamic-fn-redefs [static/static-resource (constantly nil)](let [handler (mw.embedding-sdk-bundle/serve-chunk-handler "embedding-sdk-chunk-nonexistent.js")resp (handler {:headers {}})](is (= 404 (:status resp)))diff --git a/test/metabase/server/middleware/sdk_test.clj b/test/metabase/server/middleware/sdk_test.cljindex 9ae0a1b03d1..a5e62c42324 100644--- a/test/metabase/server/middleware/sdk_test.clj+++ b/test/metabase/server/middleware/sdk_test.clj@@ -143,7 +143,7 @@(deftest embeding-mw-does-not-bump-metrics-with-random-sdk-header(let [prometheus-standin (atom {})]- (with-redefs [analytics/inc! (fn [k _] (swap! prometheus-standin update k (fnil inc 0)))]+ (mt/with-dynamic-fn-redefs [analytics/inc! (fn [k _] (swap! prometheus-standin update k (fnil inc 0)))];; has X-Metabase-Client header, but it's not the SDK, so we don't track it(let [request (mock-request {:client "my-client"})good (analytics.core/embedding-mw (fn [_ respond _] (respond {:status 200})))@@ -158,7 +158,7 @@(deftest embeding-mw-does-not-bump-sdk-metrics-without-sdk-header(let [prometheus-standin (atom {})]- (with-redefs [analytics/inc! (fn [k _] (swap! prometheus-standin update k (fnil inc 0)))]+ (mt/with-dynamic-fn-redefs [analytics/inc! (fn [k _] (swap! prometheus-standin update k (fnil inc 0)))](let [request (mock-request {}) ;; <= no X-Metabase-Client header => no SDK contextgood (analytics.core/embedding-mw (fn [_ respond _] (respond {:status 200})))bad (analytics.core/embedding-mw (fn [_ respond _] (respond {:status 400})))diff --git a/test/metabase/server/middleware/security_test.clj b/test/metabase/server/middleware/security_test.cljindex 8b61a74c6a1..8387ffc286d 100644--- a/test/metabase/server/middleware/security_test.clj+++ b/test/metabase/server/middleware/security_test.clj@@ -82,7 +82,9 @@(deftest nonce-test(testing "The nonce in the CSP header should match the nonce in the HTML from a index.html request"(let [nonceJSON (atom nil)- render-file stencil/render-file]+ render-file (mt/original-fn #'stencil/render-file)]+ ;; http/get hits a real Jetty server; handler thread doesn't inherit *local-redefs*.+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}(with-redefs [stencil/render-file (fn [path variables](reset! nonceJSON (:nonceJSON variables));; Use index_template.html instead of index.html so the frontend doesn'tdiff --git a/test/metabase/server/middleware/session_test.clj b/test/metabase/server/middleware/session_test.cljindex 4261a67beac..7e614234571 100644--- a/test/metabase/server/middleware/session_test.clj+++ b/test/metabase/server/middleware/session_test.clj@@ -281,7 +281,7 @@(testing "is `true` if advanced-permisison is enabled";; a trick to run this test in OSS because even if advanced-permisison is enabled but EE ns is not evailable;; `enable-advanced-permissions?` will still return false- (with-redefs [premium-features/enable-advanced-permissions? (fn [& _args] true)]+ (mt/with-dynamic-fn-redefs [premium-features/enable-advanced-permissions? (fn [& _args] true)](is (true?(:is-group-manager? (#'mw.session/current-user-info-for-session test-session-key nil)))))))(finallydiff --git a/test/metabase/server/middleware/settings_cache_test.clj b/test/metabase/server/middleware/settings_cache_test.cljindex 0837df07ebc..12134ebd010 100644--- a/test/metabase/server/middleware/settings_cache_test.clj+++ b/test/metabase/server/middleware/settings_cache_test.clj@@ -48,6 +48,8 @@(let [calls (atom 0)];; value in 2042 to simulate client has more recent settings(update-cookie cs cookie-name "2042-12-02+19%3A57%3A49.775909%2B00")+ ;; user-real-request hits a real Jetty server; handler thread doesn't inherit *local-redefs*.+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}(with-redefs [setting/restore-cache! (fn [] (swap! calls inc))](mt/user-real-request :crowberto :get 200 "user/current"{:request-options {:cookie-store cs}})diff --git a/test/metabase/server/streaming_response_test.clj b/test/metabase/server/streaming_response_test.cljindex c02a123c6b8..59ea01e4d70 100644--- a/test/metabase/server/streaming_response_test.clj+++ b/test/metabase/server/streaming_response_test.clj@@ -40,7 +40,7 @@(.namingPattern "streaming-response-test-thread-pool-%d");; Daemon threads do not block shutdown of the JVM(.daemon true))))]- (with-redefs [thread-pool/thread-pool (constantly pool)]+ (mt/with-dynamic-fn-redefs [thread-pool/thread-pool (constantly pool)](try(thunk)(finallydiff --git a/test/metabase/session/api_test.clj b/test/metabase/session/api_test.cljindex 204caa3d57c..c93726da9e6 100644--- a/test/metabase/session/api_test.clj+++ b/test/metabase/session/api_test.clj@@ -529,7 +529,7 @@(testing "Authenticated settings manager"(mt/with-test-user :lucky- (with-redefs [metabase.settings.models.setting/has-advanced-setting-access? (constantly true)]+ (mt/with-dynamic-fn-redefs [metabase.settings.models.setting/has-advanced-setting-access? (constantly true)](is (= (set (keys (setting/user-readable-values-map #{:public :authenticated :settings-manager :admin-write-authed-read})))(set (keys (mt/user-http-request :lucky :get 200 "session/properties"))))))))@@ -585,6 +585,8 @@(mt/with-model-cleanup [:model/User](t2/insert! :model/User (merge (mt/with-temp-defaults :model/User) {:email "[email protected]" :is_active true}))(testing "Google auth works with remember me and rasta"+ ;; client-real-response hits a real Jetty server; handler thread doesn't inherit *local-redefs*.+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}(with-redefs [http/post (constantly{:status 200:body (str "{\"aud\":\"pretend-client-id.apps.googleusercontent.com\","@@ -606,13 +608,13 @@:is_active true:first_name "last":last_name "luser"}]- (with-redefs [http/post (constantly- {:status 200- :body (str "{\"aud\":\"pretend-client-id.apps.googleusercontent.com\","- "\"email_verified\":\"true\","- "\"given_name\":\"test\","- "\"family_name\":\"user\","- "\"email\":\"[email protected]\"}")})]+ (mt/with-dynamic-fn-redefs [http/post (constantly+ {:status 200+ :body (str "{\"aud\":\"pretend-client-id.apps.googleusercontent.com\","+ "\"email_verified\":\"true\","+ "\"given_name\":\"test\","+ "\"family_name\":\"user\","+ "\"email\":\"[email protected]\"}")})](testing "with throttling enabled"(is (malli= SessionResponse(mt/client :post 200 "session/google_auth" {:token "foo"})))@@ -625,13 +627,13 @@(mt/client :post 200 "session/google_auth" {:token "foo"}))))))))(testing "Google auth throws exception for a disabled account"(mt/with-temp [:model/User _ {:email "[email protected]" :is_active false}]- (with-redefs [http/post (constantly- {:status 200- :body (str "{\"aud\":\"pretend-client-id.apps.googleusercontent.com\","- "\"email_verified\":\"true\","- "\"given_name\":\"test\","- "\"family_name\":\"user\","- "\"email\":\"[email protected]\"}")})]+ (mt/with-dynamic-fn-redefs [http/post (constantly+ {:status 200+ :body (str "{\"aud\":\"pretend-client-id.apps.googleusercontent.com\","+ "\"email_verified\":\"true\","+ "\"given_name\":\"test\","+ "\"family_name\":\"user\","+ "\"email\":\"[email protected]\"}")})](is (= {:errors {:_error "Your account is disabled."}}(mt/client :post 401 "session/google_auth" {:token "foo"})))))))))diff --git a/test/metabase/session/models/session_test.clj b/test/metabase/session/models/session_test.cljindex da1b3c11f92..6833faabde3 100644--- a/test/metabase/session/models/session_test.clj+++ b/test/metabase/session/models/session_test.clj@@ -39,7 +39,7 @@(deftest embedding-test(testing "if request is an embedding request, we should set the anti_csrf_token"(request/with-current-request {:headers {"x-metabase-embedded" "true"}}- (with-redefs [session/random-anti-csrf-token (constantly "315c1279c6f9f873bf1face7afeee420")]+ (mt/with-dynamic-fn-redefs [session/random-anti-csrf-token (constantly "315c1279c6f9f873bf1face7afeee420")](is (=? {:id test-id:key_hashed (session/hash-session-key "092797dd-a82a-4748-b393-697d7bb9ab65"):user_id (mt/user->id :trashbird)@@ -51,21 +51,21 @@(mt/test-helpers-set-global-values!(mt/with-temp [:model/User {user-id :id, email :email, first-name :first_name}](let [device (str (random-uuid))- original-maybe-send (var-get #'metabase.login-history.record/maybe-send-login-from-new-device-email)]+ original-maybe-send (mt/original-fn #'metabase.login-history.record/maybe-send-login-from-new-device-email)](testing "send email on first login from *new* device (but not first login ever)"(mt/with-fake-inbox;; mock out the IP address geocoding function so we can make sure it handles timezones like PST correctly;; (#15603)- (with-redefs [request/geocode-ip-addresses (fn [ip-addresses]- (into {} (for [ip-address ip-addresses]- [ip-address- {:description "San Francisco, California, United States"- :timezone (t/zone-id "America/Los_Angeles")}])))- metabase.login-history.record/maybe-send-login-from-new-device-email- (fn [login-history]- (when-let [futur (original-maybe-send login-history)]+ (mt/with-dynamic-fn-redefs [request/geocode-ip-addresses (fn [ip-addresses]+ (into {} (for [ip-address ip-addresses]+ [ip-address+ {:description "San Francisco, California, United States"+ :timezone (t/zone-id "America/Los_Angeles")}])))+ metabase.login-history.record/maybe-send-login-from-new-device-email+ (fn [login-history]+ (when-let [futur (original-maybe-send login-history)];; block in tests- (u/deref-with-timeout futur 10000)))]+ (u/deref-with-timeout futur 10000)))](mt/with-temp [:model/LoginHistory _ {:user_id user-id:device_id (str (random-uuid))}:model/LoginHistory _ {:user_id user-id@@ -118,19 +118,19 @@(deftest login-email-fall-back-name-test(mt/test-helpers-set-global-values!- (let [original-maybe-send (var-get #'metabase.login-history.record/maybe-send-login-from-new-device-email)+ (let [original-maybe-send (mt/original-fn #'metabase.login-history.record/maybe-send-login-from-new-device-email)new-login-email (fn [user-id email](mt/with-fake-inbox- (with-redefs [request/geocode-ip-addresses (fn [ip-addresses]- (into {} (for [ip-address ip-addresses]- [ip-address- {:description "San Francisco, California, United States"- :timezone (t/zone-id "America/Los_Angeles")}])))- metabase.login-history.record/maybe-send-login-from-new-device-email- (fn [login-history]- (when-let [futur (original-maybe-send login-history)]+ (mt/with-dynamic-fn-redefs [request/geocode-ip-addresses (fn [ip-addresses]+ (into {} (for [ip-address ip-addresses]+ [ip-address+ {:description "San Francisco, California, United States"+ :timezone (t/zone-id "America/Los_Angeles")}])))+ metabase.login-history.record/maybe-send-login-from-new-device-email+ (fn [login-history]+ (when-let [futur (original-maybe-send login-history)];; block in tests- (u/deref-with-timeout futur 10000)))]+ (u/deref-with-timeout futur 10000)))](let [device (str (random-uuid))](mt/with-temp [:model/LoginHistory _ {:user_id user-id:device_id (str (random-uuid))}diff --git a/test/metabase/settings/models/setting_test.clj b/test/metabase/settings/models/setting_test.cljindex 409ceb44552..262fe058b59 100644--- a/test/metabase/settings/models/setting_test.clj+++ b/test/metabase/settings/models/setting_test.clj@@ -329,15 +329,15 @@(testing "if one change fails, the entire set of changes should be reverted"(mt/with-temporary-setting-values [test-setting-1 "123"test-setting-2 "123"]- (let [orig setting/set!+ (let [orig (mt/original-fn #'setting/set!)calls (atom 0)];; allow the first Setting change to succeed, then throw an Exception after that- (with-redefs [setting/set! (fn [& args]- (if (zero? @calls)- (do- (swap! calls inc)- (apply orig args))- (throw (ex-info "Oops!" {}))))]+ (mt/with-dynamic-fn-redefs [setting/set! (fn [& args]+ (if (zero? @calls)+ (do+ (swap! calls inc)+ (apply orig args))+ (throw (ex-info "Oops!" {}))))](is (thrown-with-msg?Throwable#"Oops"@@ -578,13 +578,13 @@(deftest db-stored-value-test(testing "should expose the raw DB/cache value through the public API"(is (= "raw-value"- (with-redefs [setting/db-or-cache-value (constantly "raw-value")]+ (mt/with-dynamic-fn-redefs [setting/db-or-cache-value (constantly "raw-value")](setting/db-stored-value :test-setting-1))))));;; -------------------------------------------------- CSV Settings --------------------------------------------------(defn- fetch-csv-setting-value! [v]- (with-redefs [setting/db-or-cache-value (constantly v)]+ (mt/with-dynamic-fn-redefs [setting/db-or-cache-value (constantly v)](test-csv-setting)))(deftest get-csv-setting-test@@ -826,7 +826,7 @@(testing setting(is (= expected (setting/can-read-setting? setting (setting/current-user-readable-visibilities))))))))(testing "non-admin user with advanced setting access"- (with-redefs [setting/has-advanced-setting-access? (constantly true)]+ (mt/with-dynamic-fn-redefs [setting/has-advanced-setting-access? (constantly true)](mt/with-current-user (mt/user->id :rasta)(doseq [[setting expected] {:test-public-setting true:test-authenticated-setting true@@ -1439,7 +1439,7 @@(validate tag value)))))))))(deftest validate-description-translation-test- (with-redefs [setting/ns-in-test? (constantly false)]+ (mt/with-dynamic-fn-redefs [setting/ns-in-test? (constantly false)](testing "When not in a test, defsetting descriptions must be i18n'ed"(try(walk/macroexpand-alldiff --git a/test/metabase/settings_rest/api_test.clj b/test/metabase/settings_rest/api_test.cljindex 4c2e118b1bb..3000f20940c 100644--- a/test/metabase/settings_rest/api_test.clj+++ b/test/metabase/settings_rest/api_test.clj@@ -64,8 +64,8 @@(defn- do-with-mocked-settings-manager-access![f]- (with-redefs [setting/has-advanced-setting-access? (constantly true)- validation/check-has-application-permission (constantly true)]+ (mt/with-dynamic-fn-redefs [setting/has-advanced-setting-access? (constantly true)+ validation/check-has-application-permission (constantly true)](f)))(defmacro ^:private with-mocked-settings-manager-access!diff --git a/test/metabase/setup_rest/api_test.clj b/test/metabase/setup_rest/api_test.cljindex b7e46550a28..a9b6d166aff 100644--- a/test/metabase/setup_rest/api_test.clj+++ b/test/metabase/setup_rest/api_test.clj@@ -238,7 +238,7 @@:email (mt/random-email):password "p@ssword1"}}has-user-setup (atom false)]- (with-redefs [setup/has-user-setup (fn [] @has-user-setup)]+ (mt/with-dynamic-fn-redefs [setup/has-user-setup (fn [] @has-user-setup)](is (not (setup/has-user-setup)))(mt/discard-setting-changes [site-name site-locale anon-tracking-enabled admin-email](is (malli= [:map {:closed true} [:id ms/NonBlankString]]diff --git a/test/metabase/slackbot/api_test.clj b/test/metabase/slackbot/api_test.cljindex c81e9792c4e..d94baad462a 100644--- a/test/metabase/slackbot/api_test.clj+++ b/test/metabase/slackbot/api_test.clj@@ -89,7 +89,7 @@(testing "POST /api/metabot/slack/events"(testing "ack events even when metabot-v3 feature is disabled to prevent Slack retries"(tu/with-slackbot-setup- (with-redefs [slackbot.settings/unobfuscated-metabot-slack-signing-secret (constantly tu/test-signing-secret)]+ (mt/with-dynamic-fn-redefs [slackbot.settings/unobfuscated-metabot-slack-signing-secret (constantly tu/test-signing-secret)](let [body (assoc-in tu/base-dm-event [:event :channel] "D123")response (mt/client :post 200 "metabot/slack/events"(tu/slack-request-options body)@@ -119,8 +119,8 @@(tu/with-slackbot-setup(let [event-body (update tu/base-dm-event :event merge {:subtype "message_deleted"})ignored (atom false)]- (with-redefs [slackbot/ignore-event (fn [_] (reset! ignored true))- slackbot/process-async (fn [& _] (throw (ex-info "process-async should not be called" {})))]+ (mt/with-dynamic-fn-redefs [slackbot/ignore-event (fn [_] (reset! ignored true))+ slackbot/process-async (fn [& _] (throw (ex-info "process-async should not be called" {})))](tu/with-slackbot-mocks{:ai-text "Should not be called"}(fn [{:keys [post-calls]}]@@ -582,7 +582,7 @@(is (= :ignored (:status (#'slackbot/authorize-delete-request "U123" "C123" nil)))))(testing "returns :ignored for unknown Slack user"- (with-redefs [slackbot/slack-id->user-id (constantly nil)]+ (mt/with-dynamic-fn-redefs [slackbot/slack-id->user-id (constantly nil)](is (= {:status :ignored:reason :unlinked-user:slack-user-id "U-UNKNOWN"@@ -591,19 +591,19 @@(#'slackbot/authorize-delete-request "U-UNKNOWN" "C123" "ts123")))))(testing "returns :ignored when response is not tracked in the DB"- (with-redefs [slackbot/slack-id->user-id (constantly (mt/user->id :rasta))- slackbot.persistence/response-owner-user-id (constantly nil)]+ (mt/with-dynamic-fn-redefs [slackbot/slack-id->user-id (constantly (mt/user->id :rasta))+ slackbot.persistence/response-owner-user-id (constantly nil)](is (= :ignored (:status (#'slackbot/authorize-delete-request "U123" "C123" "ts123"))))))(testing "returns :ignored when the requester is not the response owner"- (with-redefs [slackbot/slack-id->user-id (constantly (mt/user->id :rasta))- slackbot.persistence/response-owner-user-id (constantly (mt/user->id :crowberto))]+ (mt/with-dynamic-fn-redefs [slackbot/slack-id->user-id (constantly (mt/user->id :rasta))+ slackbot.persistence/response-owner-user-id (constantly (mt/user->id :crowberto))](is (= :ignored (:status (#'slackbot/authorize-delete-request "U123" "C123" "ts123"))))))(testing "returns :authorized when the requester owns the response"(let [user-id (mt/user->id :rasta)]- (with-redefs [slackbot/slack-id->user-id (constantly user-id)- slackbot.persistence/response-owner-user-id (constantly user-id)]+ (mt/with-dynamic-fn-redefs [slackbot/slack-id->user-id (constantly user-id)+ slackbot.persistence/response-owner-user-id (constantly user-id)](is (= {:status :authorized:channel-id "C123":message-ts "ts123"@@ -762,10 +762,10 @@(testing "feedback action opens modal with correct private_metadata"(let [conversation-id "conv-123"open-view-calls (atom [])]- (with-redefs [slackbot/slack-id->user-id (constantly (mt/user->id :rasta))- slackbot.client/open-view (fn [_ params]- (swap! open-view-calls conj params)- {:ok true})]+ (mt/with-dynamic-fn-redefs [slackbot/slack-id->user-id (constantly (mt/user->id :rasta))+ slackbot.client/open-view (fn [_ params]+ (swap! open-view-calls conj params)+ {:ok true})](let [action {:action_id "metabot_feedback":value (json/encode {:conversation_id conversation-id :positive true})}](#'slackbot/handle-feedback-action@@ -788,10 +788,10 @@(deftest handle-feedback-action-negative-test(testing "negative feedback action opens modal with issue type dropdown"(let [open-view-calls (atom [])]- (with-redefs [slackbot/slack-id->user-id (constantly (mt/user->id :rasta))- slackbot.client/open-view (fn [_ params]- (swap! open-view-calls conj params)- {:ok true})]+ (mt/with-dynamic-fn-redefs [slackbot/slack-id->user-id (constantly (mt/user->id :rasta))+ slackbot.client/open-view (fn [_ params]+ (swap! open-view-calls conj params)+ {:ok true})](let [action {:action_id "metabot_feedback":value (json/encode {:conversation_id "conv-123" :positive false})}](#'slackbot/handle-feedback-action@@ -807,10 +807,10 @@(deftest handle-feedback-action-unauthenticated-test(testing "feedback action is silently skipped for unauthenticated user"(let [open-view-calls (atom [])]- (with-redefs [slackbot/slack-id->user-id (constantly nil)- slackbot.client/open-view (fn [_ params]- (swap! open-view-calls conj params)- {:ok true})]+ (mt/with-dynamic-fn-redefs [slackbot/slack-id->user-id (constantly nil)+ slackbot.client/open-view (fn [_ params]+ (swap! open-view-calls conj params)+ {:ok true})](let [action {:action_id "metabot_feedback":value (json/encode {:conversation_id "conv-456" :positive false})}result (#'slackbot/handle-feedback-action@@ -1045,10 +1045,10 @@(deftest conversation-permalink-returns-nil-when-slack-not-configured-test(testing "conversation-permalink does not call Slack when slack-configured? is false"(let [client-calls (atom 0)]- (with-redefs [channel.settings/slack-configured? (constantly false)- slackbot.client/get-permalink (fn [& _]- (swap! client-calls inc)- {:ok true :permalink "should-not-be-returned"})]+ (mt/with-dynamic-fn-redefs [channel.settings/slack-configured? (constantly false)+ slackbot.client/get-permalink (fn [& _]+ (swap! client-calls inc)+ {:ok true :permalink "should-not-be-returned"})](is (nil? (slackbot/conversation-permalink "C123" "1.0")))(is (zero? @client-calls)"no slack client call when not configured")))))@@ -1056,39 +1056,39 @@(deftest conversation-permalink-returns-nil-when-channel-or-ts-missing-test(testing "conversation-permalink short-circuits to nil when channel or ts is missing — no client call"(let [client-calls (atom 0)]- (with-redefs [channel.settings/slack-configured? (constantly true)- channel.settings/unobfuscated-slack-app-token (constantly "xoxb-test")- slackbot.client/get-permalink (fn [& _]- (swap! client-calls inc)- {:ok true})]+ (mt/with-dynamic-fn-redefs [channel.settings/slack-configured? (constantly true)+ channel.settings/unobfuscated-slack-app-token (constantly "xoxb-test")+ slackbot.client/get-permalink (fn [& _]+ (swap! client-calls inc)+ {:ok true})](is (nil? (slackbot/conversation-permalink nil "1.0")))(is (nil? (slackbot/conversation-permalink "C123" nil)))(is (zero? @client-calls))))))(deftest conversation-permalink-happy-path-test(testing "conversation-permalink returns the Slack permalink string when ok is true"- (with-redefs [channel.settings/slack-configured? (constantly true)- channel.settings/unobfuscated-slack-app-token (constantly "xoxb-test")- slackbot.client/get-permalink (fn [_client {:keys [channel ts]}]- {:ok true- :permalink (format "https://slack.example/%s/%s" channel ts)})]+ (mt/with-dynamic-fn-redefs [channel.settings/slack-configured? (constantly true)+ channel.settings/unobfuscated-slack-app-token (constantly "xoxb-test")+ slackbot.client/get-permalink (fn [_client {:keys [channel ts]}]+ {:ok true+ :permalink (format "https://slack.example/%s/%s" channel ts)})](is (= "https://slack.example/C123/1.0"(slackbot/conversation-permalink "C123" "1.0"))))))(deftest conversation-permalink-returns-nil-when-slack-says-not-ok-test(testing "conversation-permalink returns nil when Slack responds with {:ok false}"- (with-redefs [channel.settings/slack-configured? (constantly true)- channel.settings/unobfuscated-slack-app-token (constantly "xoxb-test")- slackbot.client/get-permalink (fn [& _]- {:ok false :error "channel_not_found"})]+ (mt/with-dynamic-fn-redefs [channel.settings/slack-configured? (constantly true)+ channel.settings/unobfuscated-slack-app-token (constantly "xoxb-test")+ slackbot.client/get-permalink (fn [& _]+ {:ok false :error "channel_not_found"})](is (nil? (slackbot/conversation-permalink "C123" "1.0"))))))(deftest conversation-permalink-swallows-client-exception-test(testing "exceptions from the Slack client are caught — function returns nil rather than propagating"- (with-redefs [channel.settings/slack-configured? (constantly true)- channel.settings/unobfuscated-slack-app-token (constantly "xoxb-test")- slackbot.client/get-permalink (fn [& _]- (throw (ex-info "slack down" {})))]+ (mt/with-dynamic-fn-redefs [channel.settings/slack-configured? (constantly true)+ channel.settings/unobfuscated-slack-app-token (constantly "xoxb-test")+ slackbot.client/get-permalink (fn [& _]+ (throw (ex-info "slack down" {})))](is (nil? (slackbot/conversation-permalink "C123" "1.0"))))));; -------------------------------- Visualization Integration Tests --------------------------------@@ -1306,7 +1306,7 @@(tu/with-slackbot-mocks{:ai-text "Hello!"}(fn [_]- (with-redefs [slackbot.streaming/send-response (fn [& _] (throw (Exception. "boom")))]+ (mt/with-dynamic-fn-redefs [slackbot.streaming/send-response (fn [& _] (throw (Exception. "boom")))](let [response (mt/client :post 200 "metabot/slack/events"(tu/slack-request-options tu/base-dm-event) tu/base-dm-event)](is (= "ok" response))@@ -1326,8 +1326,8 @@(let [channel-id "C123"message-ts "1234567890.000001"user-id (mt/user->id :rasta)]- (with-redefs [slackbot.client/update-message (constantly {:ok true})- slackbot.persistence/soft-delete-response! (constantly true)]+ (mt/with-dynamic-fn-redefs [slackbot.client/update-message (constantly {:ok true})+ slackbot.persistence/soft-delete-response! (constantly true)](#'slackbot/replace-response-with-removed-notice!{:token "xoxb-test"} channel-id message-ts user-id)(is (prometheus-test/approx= 1 (mt/metric-value system :metabase-slackbot/responses-deleted)))))))))diff --git a/test/metabase/slackbot/channel_test.clj b/test/metabase/slackbot/channel_test.cljindex 6896f6a6416..8b1fe6db696 100644--- a/test/metabase/slackbot/channel_test.clj+++ b/test/metabase/slackbot/channel_test.clj@@ -3,16 +3,17 @@[clojure.test :refer :all][metabase.metabot.persistence :as metabot.persistence][metabase.slackbot.channel :as slackbot.channel]- [metabase.slackbot.client :as slackbot.client]))+ [metabase.slackbot.client :as slackbot.client]+ [metabase.test :as mt]))(deftest channel-response-passes-slack-metadata-for-deep-linking-test(let [request-opts (atom nil)backfill-args (atom nil)]- (with-redefs [slackbot.client/set-status (constantly {:ok true})- slackbot.client/post-thread-reply (constantly {:ok true :ts "1700000000.000002"})- metabot.persistence/set-response-slack-msg-id!- (fn [msg-id slack-msg-id]- (reset! backfill-args {:msg-id msg-id :slack-msg-id slack-msg-id}))]+ (mt/with-dynamic-fn-redefs [slackbot.client/set-status (constantly {:ok true})+ slackbot.client/post-thread-reply (constantly {:ok true :ts "1700000000.000002"})+ metabot.persistence/set-response-slack-msg-id!+ (fn [msg-id slack-msg-id]+ (reset! backfill-args {:msg-id msg-id :slack-msg-id slack-msg-id}))](slackbot.channel/send-channel-response{}{:ts "1700000000.000001"}diff --git a/test/metabase/slackbot/streaming_test.clj b/test/metabase/slackbot/streaming_test.cljindex d22ff0afee4..da2660e89f3 100644--- a/test/metabase/slackbot/streaming_test.clj+++ b/test/metabase/slackbot/streaming_test.clj@@ -41,17 +41,17 @@(deftest thread->history-strips-bot-mentions-test(testing "User messages have bot mentions stripped"- (with-redefs [slackbot.persistence/message-history (constantly {})]+ (mt/with-dynamic-fn-redefs [slackbot.persistence/message-history (constantly {})](let [thread {:messages [{:ts "1709567890.000001" :text "<@UBOT123> hello" :user "U123"}]}result (#'slackbot.streaming/thread->history thread "UBOT123" "conv-123")](is (= [{:role :user :content "hello"}] result))))))(deftest thread->history-merges-tool-calls-test(testing "Bot messages include tool call data from DB before text"- (with-redefs [slackbot.persistence/message-history- (constantly {"1709567890.000002"- [{:role :assistant :tool_calls [{:id "tc1" :name "run_query"}]}- {:role :tool :tool_call_id "tc1" :content "42"}]})]+ (mt/with-dynamic-fn-redefs [slackbot.persistence/message-history+ (constantly {"1709567890.000002"+ [{:role :assistant :tool_calls [{:id "tc1" :name "run_query"}]}+ {:role :tool :tool_call_id "tc1" :content "42"}]})](let [thread {:messages [{:ts "1709567890.000002" :text "The answer is 42" :bot_id "B123"}]}result (#'slackbot.streaming/thread->history thread "UBOT123" "conv-123")](is (= 3 (count result)))@@ -61,7 +61,7 @@(deftest thread->history-excludes-thinking-test(testing "Thinking placeholder messages are excluded from history"- (with-redefs [slackbot.persistence/message-history (constantly {})]+ (mt/with-dynamic-fn-redefs [slackbot.persistence/message-history (constantly {})](let [thread {:messages [{:ts "1709567890.000001" :text "question" :user "U123"}{:ts "1709567890.000002" :text "_Thinking..._" :bot_id "B123"}]}result (#'slackbot.streaming/thread->history thread "UBOT123" "conv-123")]@@ -70,7 +70,7 @@(deftest thread->history-excludes-blank-bot-messages-test(testing "Bot messages with blank text are excluded"- (with-redefs [slackbot.persistence/message-history (constantly {})]+ (mt/with-dynamic-fn-redefs [slackbot.persistence/message-history (constantly {})](let [thread {:messages [{:ts "1709567890.000001" :text "" :bot_id "B123"}{:ts "1709567890.000002" :text " " :bot_id "B123"}{:ts "1709567890.000003" :text "real" :bot_id "B123"}]}@@ -79,9 +79,9 @@(deftest thread->history-excludes-soft-deleted-bot-messages-test(testing "thread->history excludes bot messages that have been soft-deleted"- (with-redefs [slackbot.persistence/message-history (constantly {})- slackbot.persistence/deleted-message-ids- (fn [_conv-id _ids] #{"1709567890.000002"})]+ (mt/with-dynamic-fn-redefs [slackbot.persistence/message-history (constantly {})+ slackbot.persistence/deleted-message-ids+ (fn [_conv-id _ids] #{"1709567890.000002"})](let [thread {:messages [{:ts "1709567890.000001" :text "User question" :user "U123"}{:ts "1709567890.000002" :text "Deleted bot response" :bot_id "B123"}{:ts "1709567890.000003" :text "Live bot response" :bot_id "B123"}]}@@ -162,17 +162,17 @@event {:channel "C1" :ts "123.456" :channel_type "im"}](mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider"metabase/anthropic/claude-sonnet-4-6"]- (with-redefs [premium-features/token-status- (constantly {:meters {:anthropic:claude-sonnet-4-6:tokens {:meter-value 1000000- :is-locked true}}})- slackbot.events/event->reply-context- (constantly {:channel "C1" :thread_ts "123.456"})- slackbot.events/dm?- (constantly true)- slackbot.client/post-thread-reply- (fn [_ message-ctx text & _]- (reset! posted-message {:message-ctx message-ctx :text text})- {:ok true})]+ (mt/with-dynamic-fn-redefs [premium-features/token-status+ (constantly {:meters {:anthropic:claude-sonnet-4-6:tokens {:meter-value 1000000+ :is-locked true}}})+ slackbot.events/event->reply-context+ (constantly {:channel "C1" :thread_ts "123.456"})+ slackbot.events/dm?+ (constantly true)+ slackbot.client/post-thread-reply+ (fn [_ message-ctx text & _]+ (reset! posted-message {:message-ctx message-ctx :text text})+ {:ok true})](slackbot.streaming/send-response {:token "xoxb-test"} event)(is (= {:message-ctx {:channel "C1" :thread_ts "123.456"}:text "You've used all of your included AI service tokens. To keep using AI features, end your trial early and start your subscription, or add your own AI provider API key."}@@ -188,14 +188,14 @@{:ai-text "Hello!"}(fn [{:keys [stop-stream-calls]}](mt/with-temporary-setting-values [llm-metabot-provider "metabase/anthropic/claude-sonnet-4-6"]- (with-redefs [premium-features/token-status- (constantly nil)- metabot.persistence/start-turn!- (fn [_conv-id _profile-id _user-message & {:as opts}]- (swap! start-opts conj opts)- {:assistant-msg-id 1 :assistant-external-id "ext"})- metabot.persistence/finalize-assistant-turn!- (fn [& _] nil)]+ (mt/with-dynamic-fn-redefs [premium-features/token-status+ (constantly nil)+ metabot.persistence/start-turn!+ (fn [_conv-id _profile-id _user-message & {:as opts}]+ (swap! start-opts conj opts)+ {:assistant-msg-id 1 :assistant-external-id "ext"})+ metabot.persistence/finalize-assistant-turn!+ (fn [& _] nil)](mt/client :post 200 "metabot/slack/events"(tu/slack-request-options event-body)event-body)@@ -214,13 +214,13 @@(tu/with-slackbot-mocks{:ai-text "Hello!"}(fn [_ctx]- (with-redefs [metabot.persistence/start-turn!- (fn [_conv-id _profile-id _user-message & {:as opts}]- (deliver stored opts)- {:assistant-msg-id 1 :assistant-external-id "ext"})+ (mt/with-dynamic-fn-redefs [metabot.persistence/start-turn!+ (fn [_conv-id _profile-id _user-message & {:as opts}]+ (deliver stored opts)+ {:assistant-msg-id 1 :assistant-external-id "ext"});; Force setup to throw *after* start-turn! has run.- slackbot.persistence/message-history- (fn [& _] (throw (ex-info "boom" {})))]+ slackbot.persistence/message-history+ (fn [& _] (throw (ex-info "boom" {})))](mt/client :post 200 "metabot/slack/events"(tu/slack-request-options event-body)event-body)@@ -241,12 +241,12 @@{:ai-text "Hello!"}(fn [{:keys [stop-stream-calls]}](mt/with-temporary-setting-values [analytics-pii-retention-enabled flag-on?]- (with-redefs [metabot.persistence/start-turn!- (fn [_conv-id _profile-id _user-message & {:as opts}]- (swap! start-opts conj opts)- {:assistant-msg-id 1 :assistant-external-id "ext"})- metabot.persistence/finalize-assistant-turn!- (fn [& _] nil)]+ (mt/with-dynamic-fn-redefs [metabot.persistence/start-turn!+ (fn [_conv-id _profile-id _user-message & {:as opts}]+ (swap! start-opts conj opts)+ {:assistant-msg-id 1 :assistant-external-id "ext"})+ metabot.persistence/finalize-assistant-turn!+ (fn [& _] nil)](mt/client :post 200 "metabot/slack/events"(tu/slack-request-options event-body)event-body)@@ -268,12 +268,12 @@{:ai-text "Hello!"}(fn [{:keys [stop-stream-calls]}](mt/with-temporary-setting-values [llm-metabot-provider "anthropic/claude-haiku-4-5"]- (with-redefs [metabot.persistence/start-turn!- (fn [_conv-id _profile-id _user-message & {:as opts}]- (swap! start-opts conj opts)- {:assistant-msg-id 1 :assistant-external-id "ext"})- metabot.persistence/finalize-assistant-turn!- (fn [& _] nil)]+ (mt/with-dynamic-fn-redefs [metabot.persistence/start-turn!+ (fn [_conv-id _profile-id _user-message & {:as opts}]+ (swap! start-opts conj opts)+ {:assistant-msg-id 1 :assistant-external-id "ext"})+ metabot.persistence/finalize-assistant-turn!+ (fn [& _] nil)](mt/client :post 200 "metabot/slack/events"(tu/slack-request-options event-body)event-body)diff --git a/test/metabase/sso/api/ldap_test.clj b/test/metabase/sso/api/ldap_test.cljindex 02482f45784..5a1c4f96a66 100644--- a/test/metabase/sso/api/ldap_test.clj+++ b/test/metabase/sso/api/ldap_test.clj@@ -63,7 +63,7 @@(mt/user-http-request :crowberto :put 500 "ldap/settings"(assoc (ldap-test-details false) :ldap-password "wrong-password")))- (with-redefs [ldap/test-ldap-connection (constantly {:status :SUCCESS})]+ (mt/with-dynamic-fn-redefs [ldap/test-ldap-connection (constantly {:status :SUCCESS})](testing "LDAP port is saved as default value if passed as an empty string (#18936)"(is (true?(mt/user-http-request :crowberto :put 200 "ldap/settings"diff --git a/test/metabase/sso/common_test.clj b/test/metabase/sso/common_test.cljindex 4c37e5f9fd6..d4d4f77ced1 100644--- a/test/metabase/sso/common_test.clj+++ b/test/metabase/sso/common_test.clj@@ -135,15 +135,15 @@(mt/with-log-level :warn(mt/with-user-in-groups [user [(perms-group/admin)]](let [log-warn-count (atom #{})]- (with-redefs [t2/delete!- (fn [model & _args]- (when (= model :model/PermissionsGroupMembership)- (throw (ex-info (str perms/fail-to-remove-last-admin-msg)- {:status-code 400}))))- clojure.tools.logging/log*- (fn [_logger level _throwable msg]- (when (:= level :warn)- (swap! log-warn-count conj msg)))]+ (mt/with-dynamic-fn-redefs [t2/delete!+ (fn [model & _args]+ (when (= model :model/PermissionsGroupMembership)+ (throw (ex-info (str perms/fail-to-remove-last-admin-msg)+ {:status-code 400}))))+ clojure.tools.logging/log*+ (fn [_logger level _throwable msg]+ (when (:= level :warn)+ (swap! log-warn-count conj msg)))];; make sure sync run without throwing exception(integrations.common/sync-group-memberships! user #{} #{(perms-group/admin)});; make sure we log a msg for that@@ -231,11 +231,11 @@(testing "2-arity version: Make sure the delete last admin exception is caught"(mt/with-log-messages-for-level [messages :warn](mt/with-user-in-groups [user [(perms-group/admin)]]- (with-redefs [t2/delete!- (fn [model & _args]- (when (= model :model/PermissionsGroupMembership)- (throw (ex-info (str perms/fail-to-remove-last-admin-msg)- {:status-code 400}))))]+ (mt/with-dynamic-fn-redefs [t2/delete!+ (fn [model & _args]+ (when (= model :model/PermissionsGroupMembership)+ (throw (ex-info (str perms/fail-to-remove-last-admin-msg)+ {:status-code 400}))))];; make sure sync runs without throwing exception(integrations.common/sync-group-memberships! user #{});; make sure we log a msg for thatdiff --git a/test/metabase/sso/integrations/slack_connect_test.clj b/test/metabase/sso/integrations/slack_connect_test.cljindex 8821d423b08..396a42e5578 100644--- a/test/metabase/sso/integrations/slack_connect_test.clj+++ b/test/metabase/sso/integrations/slack_connect_test.clj@@ -297,6 +297,8 @@(mt/with-temporary-setting-values [slack-connect-user-provisioning-enabled falsesite-name "test"](with-successful-oidc!+ ;; client-real-response hits a real Jetty server; handler thread doesn't inherit *local-redefs*.+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}(with-redefs [auth-identity/login!(fn [_provider _request]{:success? falsediff --git a/test/metabase/sso/oidc/discovery_test.clj b/test/metabase/sso/oidc/discovery_test.cljindex 3e54ac0c23f..74298f572a2 100644--- a/test/metabase/sso/oidc/discovery_test.clj+++ b/test/metabase/sso/oidc/discovery_test.clj@@ -75,14 +75,14 @@(deftest discover-oidc-configuration-success-test(testing "Successfully discovers OIDC configuration"(oidc.discovery/clear-cache!)- (with-redefs [http/get (fn [url _opts]- (is (= "https://example.com/.well-known/openid-configuration" url))- {:status 200- :body {:issuer "https://example.com"- :authorization_endpoint "https://example.com/authorize"- :token_endpoint "https://example.com/token"- :jwks_uri "https://example.com/jwks"- :userinfo_endpoint "https://example.com/userinfo"}})]+ (mt/with-dynamic-fn-redefs [http/get (fn [url _opts]+ (is (= "https://example.com/.well-known/openid-configuration" url))+ {:status 200+ :body {:issuer "https://example.com"+ :authorization_endpoint "https://example.com/authorize"+ :token_endpoint "https://example.com/token"+ :jwks_uri "https://example.com/jwks"+ :userinfo_endpoint "https://example.com/userinfo"}})](let [config (oidc.discovery/discover-oidc-configuration "https://example.com")](is (some? config))(is (= "https://example.com" (:issuer config)))@@ -93,28 +93,28 @@(deftest discover-oidc-configuration-http-error-test(testing "Handles HTTP errors gracefully"(oidc.discovery/clear-cache!)- (with-redefs [http/get (fn [_url _opts]- {:status 404- :body "Not Found"})]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts]+ {:status 404+ :body "Not Found"})](let [config (oidc.discovery/discover-oidc-configuration "https://example.org")](is (nil? config))))))(deftest discover-oidc-configuration-exception-test(testing "Handles exceptions gracefully"(oidc.discovery/clear-cache!)- (with-redefs [http/get (fn [_url _opts]- (throw (ex-info "Connection timeout" {})))]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts]+ (throw (ex-info "Connection timeout" {})))](let [config (oidc.discovery/discover-oidc-configuration "https://example.net")](is (nil? config))))))(deftest discover-oidc-configuration-trailing-slash-test(testing "Strips trailing slash from issuer URI"(oidc.discovery/clear-cache!)- (with-redefs [http/get (fn [url _opts]- (is (= "https://example.edu/.well-known/openid-configuration" url))- {:status 200- :body {:issuer "https://example.edu"- :authorization_endpoint "https://example.edu/authorize"}})]+ (mt/with-dynamic-fn-redefs [http/get (fn [url _opts]+ (is (= "https://example.edu/.well-known/openid-configuration" url))+ {:status 200+ :body {:issuer "https://example.edu"+ :authorization_endpoint "https://example.edu/authorize"}})](let [config (oidc.discovery/discover-oidc-configuration "https://example.edu/")](is (some? config))))))@@ -130,10 +130,10 @@(testing "Uses cached discovery document when cache is fresh (not expired)"(oidc.discovery/clear-cache!)(let [fetch-count (atom 0)]- (with-redefs [http/get (fn [_url _opts]- (swap! fetch-count inc)- {:status 200- :body test-discovery-doc})]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts]+ (swap! fetch-count inc)+ {:status 200+ :body test-discovery-doc})];; First call should fetch(let [result1 (oidc.discovery/discover-oidc-configuration "https://google.com")](is (some? result1))@@ -147,10 +147,10 @@(testing "Re-fetches discovery document when cache entry is expired"(oidc.discovery/clear-cache!)(let [fetch-count (atom 0)]- (with-redefs [http/get (fn [_url _opts]- (swap! fetch-count inc)- {:status 200- :body test-discovery-doc})]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts]+ (swap! fetch-count inc)+ {:status 200+ :body test-discovery-doc})];; First call should fetch(oidc.discovery/discover-oidc-configuration "https://github.com")(is (= 1 @fetch-count))@@ -169,10 +169,10 @@(testing "invalidate-cache! removes cache entry for specific issuer"(oidc.discovery/clear-cache!)(let [fetch-count (atom 0)]- (with-redefs [http/get (fn [_url _opts]- (swap! fetch-count inc)- {:status 200- :body test-discovery-doc})]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts]+ (swap! fetch-count inc)+ {:status 200+ :body test-discovery-doc})];; Populate cache(oidc.discovery/discover-oidc-configuration "https://microsoft.com")(is (= 1 @fetch-count))@@ -188,10 +188,10 @@(testing "invalidate-cache! normalizes issuer URL"(oidc.discovery/clear-cache!)(let [fetch-count (atom 0)]- (with-redefs [http/get (fn [_url _opts]- (swap! fetch-count inc)- {:status 200- :body test-discovery-doc})]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts]+ (swap! fetch-count inc)+ {:status 200+ :body test-discovery-doc})];; Populate cache without trailing slash(oidc.discovery/discover-oidc-configuration "https://apple.com")(is (= 1 @fetch-count))diff --git a/test/metabase/sso/oidc/http_test.clj b/test/metabase/sso/oidc/http_test.cljindex 673fd7ff342..5533e33577b 100644--- a/test/metabase/sso/oidc/http_test.clj+++ b/test/metabase/sso/oidc/http_test.clj@@ -25,7 +25,7 @@(testing "oidc-get allows requests when oidc-allowed-networks is :allow-all"(mt/with-temporary-setting-values [oidc-allowed-networks :allow-all]- (with-redefs [http/get (fn [_url _opts] {:status 200 :body {:ok true}})]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts] {:status 200 :body {:ok true}})](let [response (oidc.http/oidc-get "https://provider.example.com/discovery")](is (= 200 (:status response))))))))@@ -46,7 +46,7 @@(testing "oidc-post allows requests when oidc-allowed-networks is :allow-all"(mt/with-temporary-setting-values [oidc-allowed-networks :allow-all]- (with-redefs [http/post (fn [_url _opts] {:status 200 :body {:access_token "tok"}})]+ (mt/with-dynamic-fn-redefs [http/post (fn [_url _opts] {:status 200 :body {:access_token "tok"}})](let [response (oidc.http/oidc-post "https://provider.example.com/token"{:form-params {:grant_type "client_credentials"}})](is (= 200 (:status response))))))))@@ -54,17 +54,17 @@(deftest oidc-get-allow-all-test(testing "oidc-get allows all hosts when oidc-allowed-networks is :allow-all"(mt/with-temporary-setting-values [oidc-allowed-networks :allow-all]- (with-redefs [http/get (fn [_url _opts] {:status 200 :body {}})]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts] {:status 200 :body {}})](is (= 200 (:status (oidc.http/oidc-get "http://192.168.1.1/path"))))))))(deftest oidc-get-merges-custom-opts-test(testing "Custom options are merged with defaults"(mt/with-temporary-setting-values [oidc-allowed-networks :allow-all]- (with-redefs [http/get (fn [_url opts]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url opts];; Verify custom opts are present alongside defaults- (is (= :json (:as opts)))- (is (= :json (:accept opts)))- (is (= 5000 (:conn-timeout opts)))- (is (false? (:throw-exceptions opts)))- {:status 200 :body {}})]+ (is (= :json (:as opts)))+ (is (= :json (:accept opts)))+ (is (= 5000 (:conn-timeout opts)))+ (is (false? (:throw-exceptions opts)))+ {:status 200 :body {}})](oidc.http/oidc-get "https://example.com/path" {:accept :json})))))diff --git a/test/metabase/sso/oidc/tokens_test.clj b/test/metabase/sso/oidc/tokens_test.cljindex 9e98356242f..3bfbdf2f1d4 100644--- a/test/metabase/sso/oidc/tokens_test.clj+++ b/test/metabase/sso/oidc/tokens_test.clj@@ -115,9 +115,9 @@ h0ccjghRm1/Az8L/HL+gdQmtY0NdB4Ml2mZHCVsPYf5WzIirTpjY0EzKDA==config {:jwks-uri "https://provider.com/jwks":issuer-uri "https://provider.com":client-id "test-client-id"}]- (with-redefs [http/get (fn [_url _opts]- {:status 200- :body @test-jwks})]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts]+ {:status 200+ :body @test-jwks})](let [result (oidc.tokens/validate-id-token token config "test-nonce")](is (true? (:valid? result)))(is (some? (:claims result)))@@ -132,9 +132,9 @@ h0ccjghRm1/Az8L/HL+gdQmtY0NdB4Ml2mZHCVsPYf5WzIirTpjY0EzKDA==config {:jwks-uri "https://provider.com/jwks":issuer-uri "https://provider.com":client-id "test-client-id"}]- (with-redefs [http/get (fn [_url _opts]- {:status 200- :body @test-jwks})]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts]+ {:status 200+ :body @test-jwks})](let [result (oidc.tokens/validate-id-token token config "test-nonce")](is (false? (:valid? result)))(is (some? (:error result))))))))@@ -155,9 +155,9 @@ h0ccjghRm1/Az8L/HL+gdQmtY0NdB4Ml2mZHCVsPYf5WzIirTpjY0EzKDA==config {:jwks-uri "https://provider.com/jwks":issuer-uri "https://provider.com":client-id "test-client-id"}]- (with-redefs [http/get (fn [_url _opts]- {:status 200- :body @test-jwks})]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts]+ {:status 200+ :body @test-jwks})](let [result (oidc.tokens/validate-id-token token config "test-nonce")](is (false? (:valid? result)))(is (some? (:error result))))))))@@ -178,9 +178,9 @@ h0ccjghRm1/Az8L/HL+gdQmtY0NdB4Ml2mZHCVsPYf5WzIirTpjY0EzKDA==config {:jwks-uri "https://provider.com/jwks":issuer-uri "https://provider.com":client-id "test-client-id"}]- (with-redefs [http/get (fn [_url _opts]- {:status 200- :body @test-jwks})]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts]+ {:status 200+ :body @test-jwks})](let [result (oidc.tokens/validate-id-token token config "test-nonce")](is (false? (:valid? result)))(is (some? (:error result))))))))@@ -201,9 +201,9 @@ h0ccjghRm1/Az8L/HL+gdQmtY0NdB4Ml2mZHCVsPYf5WzIirTpjY0EzKDA==config {:jwks-uri "https://provider.com/jwks":issuer-uri "https://provider.com":client-id "test-client-id"}]- (with-redefs [http/get (fn [_url _opts]- {:status 200- :body @test-jwks})]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts]+ {:status 200+ :body @test-jwks})](let [result (oidc.tokens/validate-id-token token config "test-nonce")](is (false? (:valid? result)))(is (some? (:error result))))))))@@ -224,9 +224,9 @@ h0ccjghRm1/Az8L/HL+gdQmtY0NdB4Ml2mZHCVsPYf5WzIirTpjY0EzKDA==config {:jwks-uri "https://provider.com/jwks":issuer-uri "https://provider.com":client-id "test-client-id"}]- (with-redefs [http/get (fn [_url _opts]- {:status 200- :body @test-jwks})]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts]+ {:status 200+ :body @test-jwks})](let [result (oidc.tokens/validate-id-token token config "test-nonce")](is (false? (:valid? result)))(is (some? (:error result))))))))@@ -247,9 +247,9 @@ h0ccjghRm1/Az8L/HL+gdQmtY0NdB4Ml2mZHCVsPYf5WzIirTpjY0EzKDA==config {:jwks-uri "https://provider.com/jwks":issuer-uri "https://provider.com":client-id "test-client-id"}]- (with-redefs [http/get (fn [_url _opts]- {:status 200- :body @test-jwks})]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts]+ {:status 200+ :body @test-jwks})](let [result (oidc.tokens/validate-id-token token config "test-nonce")](is (true? (:valid? result))))))))@@ -260,8 +260,8 @@ h0ccjghRm1/Az8L/HL+gdQmtY0NdB4Ml2mZHCVsPYf5WzIirTpjY0EzKDA==config {:jwks-uri "https://provider.com/jwks":issuer-uri "https://provider.com":client-id "test-client-id"}]- (with-redefs [http/get (fn [_url _opts]- (throw (ex-info "Network error" {})))]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts]+ (throw (ex-info "Network error" {})))](let [result (oidc.tokens/validate-id-token token config "test-nonce")](is (false? (:valid? result)))(is (some? (:error result))))))))@@ -273,9 +273,9 @@ h0ccjghRm1/Az8L/HL+gdQmtY0NdB4Ml2mZHCVsPYf5WzIirTpjY0EzKDA==config {:jwks-uri "https://provider.com/jwks":issuer-uri "https://provider.com":client-id "test-client-id"}]- (with-redefs [http/get (fn [_url _opts]- {:status 200- :body @test-jwks})]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts]+ {:status 200+ :body @test-jwks})](let [result (oidc.tokens/validate-id-token token config "test-nonce")](is (false? (:valid? result)))(is (some? (:error result))))))))@@ -286,10 +286,10 @@ h0ccjghRm1/Az8L/HL+gdQmtY0NdB4Ml2mZHCVsPYf5WzIirTpjY0EzKDA==(testing "Uses cached JWKS when cache is fresh (not expired)"(oidc.tokens/clear-jwks-cache!)(let [fetch-count (atom 0)]- (with-redefs [http/get (fn [_url _opts]- (swap! fetch-count inc)- {:status 200- :body @test-jwks})]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts]+ (swap! fetch-count inc)+ {:status 200+ :body @test-jwks})];; First call should fetch(let [result1 (oidc.tokens/get-jwks "https://provider.com/jwks")](is (some? result1))@@ -303,10 +303,10 @@ h0ccjghRm1/Az8L/HL+gdQmtY0NdB4Ml2mZHCVsPYf5WzIirTpjY0EzKDA==(testing "Re-fetches JWKS when cache entry is expired"(oidc.tokens/clear-jwks-cache!)(let [fetch-count (atom 0)]- (with-redefs [http/get (fn [_url _opts]- (swap! fetch-count inc)- {:status 200- :body @test-jwks})]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts]+ (swap! fetch-count inc)+ {:status 200+ :body @test-jwks})];; First call should fetch(oidc.tokens/get-jwks "https://github.com/jwks")(is (= 1 @fetch-count))@@ -325,10 +325,10 @@ h0ccjghRm1/Az8L/HL+gdQmtY0NdB4Ml2mZHCVsPYf5WzIirTpjY0EzKDA==(testing "invalidate-jwks-cache! removes cache entry for specific URI"(oidc.tokens/clear-jwks-cache!)(let [fetch-count (atom 0)]- (with-redefs [http/get (fn [_url _opts]- (swap! fetch-count inc)- {:status 200- :body @test-jwks})]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts]+ (swap! fetch-count inc)+ {:status 200+ :body @test-jwks})];; Populate cache(oidc.tokens/get-jwks "https://provider.com/jwks")(is (= 1 @fetch-count))@@ -389,9 +389,9 @@ h0ccjghRm1/Az8L/HL+gdQmtY0NdB4Ml2mZHCVsPYf5WzIirTpjY0EzKDA==config {:jwks-uri "https://provider.com/jwks":issuer-uri "https://provider.com":client-id "test-client-id"}]- (with-redefs [http/get (fn [_url _opts]- {:status 200- :body @test-ec-jwks})]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts]+ {:status 200+ :body @test-ec-jwks})](let [result (oidc.tokens/validate-id-token token config "test-nonce")](is (true? (:valid? result)))(is (some? (:claims result)))@@ -418,9 +418,9 @@ h0ccjghRm1/Az8L/HL+gdQmtY0NdB4Ml2mZHCVsPYf5WzIirTpjY0EzKDA==config {:jwks-uri "https://provider.com/jwks":issuer-uri "https://provider.com":client-id "test-client-id"}]- (with-redefs [http/get (fn [_url _opts]- {:status 200- :body unsupported-jwks})]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts]+ {:status 200+ :body unsupported-jwks})](let [result (oidc.tokens/validate-id-token token config "test-nonce")](is (false? (:valid? result)))(is (= "JWT signature verification failed" (:error result))))))))@@ -445,9 +445,9 @@ h0ccjghRm1/Az8L/HL+gdQmtY0NdB4Ml2mZHCVsPYf5WzIirTpjY0EzKDA==config {:jwks-uri "https://provider.com/jwks":issuer-uri "https://provider.com":client-id "test-client-id"}]- (with-redefs [http/get (fn [_url _opts]- {:status 200- :body jwks-without-alg})]+ (mt/with-dynamic-fn-redefs [http/get (fn [_url _opts]+ {:status 200+ :body jwks-without-alg})](let [result (oidc.tokens/validate-id-token token config "test-nonce")](is (true? (:valid? result)))(is (some? (:claims result)))diff --git a/test/metabase/sso/providers/oidc_test.clj b/test/metabase/sso/providers/oidc_test.cljindex d8f2bfbd927..f7b5521d492 100644--- a/test/metabase/sso/providers/oidc_test.clj+++ b/test/metabase/sso/providers/oidc_test.clj@@ -6,7 +6,8 @@[metabase.auth-identity.provider :as provider][metabase.sso.oidc.discovery :as oidc.discovery][metabase.sso.oidc.tokens :as oidc.tokens]- [metabase.sso.providers.oidc]))+ [metabase.sso.providers.oidc]+ [metabase.test :as mt]))(set! *warn-on-reflection* true)@@ -33,8 +34,8 @@(deftest authenticate-initiate-flow-test(testing "Initiates authorization flow when no code present"- (with-redefs [oidc.discovery/discover-oidc-configuration- (fn [_issuer] test-discovery-doc)]+ (mt/with-dynamic-fn-redefs [oidc.discovery/discover-oidc-configuration+ (fn [_issuer] test-discovery-doc)](let [request {:oidc-config test-config}result (provider/authenticate :provider/oidc request)](is (= :redirect (:success? result)))@@ -54,8 +55,8 @@(is (str/includes? (:redirect-url result) "https://provider.example.com/manual/authorize"))))(testing "Includes custom scopes in authorization URL"- (with-redefs [oidc.discovery/discover-oidc-configuration- (fn [_issuer] test-discovery-doc)]+ (mt/with-dynamic-fn-redefs [oidc.discovery/discover-oidc-configuration+ (fn [_issuer] test-discovery-doc)](let [config (assoc test-config :scopes ["openid" "email" "profile" "groups"])request {:oidc-config config}result (provider/authenticate :provider/oidc request)]@@ -63,8 +64,8 @@(is (str/includes? (:redirect-url result) "scope=openid%20email%20profile%20groups")))))(testing "Returns error when authorization endpoint not found"- (with-redefs [oidc.discovery/discover-oidc-configuration- (fn [_issuer] nil)]+ (mt/with-dynamic-fn-redefs [oidc.discovery/discover-oidc-configuration+ (fn [_issuer] nil)](let [request {:oidc-config test-config}result (provider/authenticate :provider/oidc request)](is (false? (:success? result)))@@ -95,12 +96,12 @@(deftest authenticate-token-exchange-test(testing "Returns error when token exchange fails"- (with-redefs [oidc.discovery/discover-oidc-configuration- (fn [_issuer] test-discovery-doc)- http/post- (fn [_url _opts]- {:status 400- :body {:error "invalid_grant"}})]+ (mt/with-dynamic-fn-redefs [oidc.discovery/discover-oidc-configuration+ (fn [_issuer] test-discovery-doc)+ http/post+ (fn [_url _opts]+ {:status 400+ :body {:error "invalid_grant"}})](let [request {:oidc-config test-config:code "auth-code-123":state "state-token-456"}@@ -109,12 +110,12 @@(is (= :token-exchange-failed (:error result))))))(testing "Returns error when token response missing id_token"- (with-redefs [oidc.discovery/discover-oidc-configuration- (fn [_issuer] test-discovery-doc)- http/post- (fn [_url _opts]- {:status 200- :body {:access_token "access-token-123"}})]+ (mt/with-dynamic-fn-redefs [oidc.discovery/discover-oidc-configuration+ (fn [_issuer] test-discovery-doc)+ http/post+ (fn [_url _opts]+ {:status 200+ :body {:access_token "access-token-123"}})](let [request {:oidc-config test-config:code "auth-code-123":state "state-token-456"}@@ -124,17 +125,17 @@(deftest authenticate-token-validation-test(testing "Returns error when token validation fails"- (with-redefs [oidc.discovery/discover-oidc-configuration- (fn [_issuer] test-discovery-doc)- http/post- (fn [_url _opts]- {:status 200- :body {:id_token "invalid-token"- :access_token "access-token-123"}})- oidc.tokens/validate-id-token- (fn [_token _config _nonce]- {:valid? false- :error "Invalid signature"})]+ (mt/with-dynamic-fn-redefs [oidc.discovery/discover-oidc-configuration+ (fn [_issuer] test-discovery-doc)+ http/post+ (fn [_url _opts]+ {:status 200+ :body {:id_token "invalid-token"+ :access_token "access-token-123"}})+ oidc.tokens/validate-id-token+ (fn [_token _config _nonce]+ {:valid? false+ :error "Invalid signature"})](let [request {:oidc-config test-config:code "auth-code-123":state "state-token-456"@@ -145,19 +146,19 @@(deftest authenticate-user-data-extraction-test(testing "Returns error when email not in claims"- (with-redefs [oidc.discovery/discover-oidc-configuration- (fn [_issuer] test-discovery-doc)- http/post- (fn [_url _opts]- {:status 200- :body {:id_token "valid-token"- :access_token "access-token-123"}})- oidc.tokens/validate-id-token- (fn [_token _config _nonce]- {:valid? true- :claims {:sub "user123"- :iss "https://provider.example.com"- :aud "test-client-id"}})]+ (mt/with-dynamic-fn-redefs [oidc.discovery/discover-oidc-configuration+ (fn [_issuer] test-discovery-doc)+ http/post+ (fn [_url _opts]+ {:status 200+ :body {:id_token "valid-token"+ :access_token "access-token-123"}})+ oidc.tokens/validate-id-token+ (fn [_token _config _nonce]+ {:valid? true+ :claims {:sub "user123"+ :iss "https://provider.example.com"+ :aud "test-client-id"}})](let [request {:oidc-config test-config:code "auth-code-123":state "state-token-456"@@ -168,22 +169,22 @@(deftest authenticate-success-test(testing "Successfully authenticates user with valid token"- (with-redefs [oidc.discovery/discover-oidc-configuration- (fn [_issuer] test-discovery-doc)- http/post- (fn [_url _opts]- {:status 200- :body {:id_token "valid-token"- :access_token "access-token-123"}})- oidc.tokens/validate-id-token- (fn [_token _config _nonce]- {:valid? true- :claims {:sub "user123"- :iss "https://provider.example.com"- :aud "test-client-id"- :email "[email protected]"- :given_name "John"- :family_name "Doe"}})]+ (mt/with-dynamic-fn-redefs [oidc.discovery/discover-oidc-configuration+ (fn [_issuer] test-discovery-doc)+ http/post+ (fn [_url _opts]+ {:status 200+ :body {:id_token "valid-token"+ :access_token "access-token-123"}})+ oidc.tokens/validate-id-token+ (fn [_token _config _nonce]+ {:valid? true+ :claims {:sub "user123"+ :iss "https://provider.example.com"+ :aud "test-client-id"+ :email "[email protected]"+ :given_name "John"+ :family_name "Doe"}})](let [request {:oidc-config test-config:code "auth-code-123":state "state-token-456"@@ -198,20 +199,20 @@(is (= "user123" (:provider-id result))))))(testing "Successfully authenticates with minimal claims"- (with-redefs [oidc.discovery/discover-oidc-configuration- (fn [_issuer] test-discovery-doc)- http/post- (fn [_url _opts]- {:status 200- :body {:id_token "valid-token"- :access_token "access-token-123"}})- oidc.tokens/validate-id-token- (fn [_token _config _nonce]- {:valid? true- :claims {:sub "user456"- :iss "https://provider.example.com"- :aud "test-client-id"- :email "[email protected]"}})]+ (mt/with-dynamic-fn-redefs [oidc.discovery/discover-oidc-configuration+ (fn [_issuer] test-discovery-doc)+ http/post+ (fn [_url _opts]+ {:status 200+ :body {:id_token "valid-token"+ :access_token "access-token-123"}})+ oidc.tokens/validate-id-token+ (fn [_token _config _nonce]+ {:valid? true+ :claims {:sub "user456"+ :iss "https://provider.example.com"+ :aud "test-client-id"+ :email "[email protected]"}})](let [request {:oidc-config test-config:code "auth-code-123":state "state-token-456"@@ -225,22 +226,22 @@(deftest authenticate-custom-attribute-mapping-test(testing "Uses custom attribute mappings when provided"- (with-redefs [oidc.discovery/discover-oidc-configuration- (fn [_issuer] test-discovery-doc)- http/post- (fn [_url _opts]- {:status 200- :body {:id_token "valid-token"- :access_token "access-token-123"}})- oidc.tokens/validate-id-token- (fn [_token _config _nonce]- {:valid? true- :claims {:sub "user789"- :iss "https://provider.example.com"- :aud "test-client-id"- :mail "[email protected]"- :first "Jane"- :last "Smith"}})]+ (mt/with-dynamic-fn-redefs [oidc.discovery/discover-oidc-configuration+ (fn [_issuer] test-discovery-doc)+ http/post+ (fn [_url _opts]+ {:status 200+ :body {:id_token "valid-token"+ :access_token "access-token-123"}})+ oidc.tokens/validate-id-token+ (fn [_token _config _nonce]+ {:valid? true+ :claims {:sub "user789"+ :iss "https://provider.example.com"+ :aud "test-client-id"+ :mail "[email protected]"+ :first "Jane"+ :last "Smith"}})](let [config (assoc test-config:attribute-email "mail":attribute-firstname "first"@@ -257,22 +258,22 @@(deftest authenticate-config-extraction-test(testing "Extracts config from :oidc-config key"- (with-redefs [oidc.discovery/discover-oidc-configuration- (fn [_issuer] test-discovery-doc)]+ (mt/with-dynamic-fn-redefs [oidc.discovery/discover-oidc-configuration+ (fn [_issuer] test-discovery-doc)](let [request {:oidc-config test-config}result (provider/authenticate :provider/oidc request)](is (= :redirect (:success? result))))))(testing "Extracts config from :auth-identity metadata"- (with-redefs [oidc.discovery/discover-oidc-configuration- (fn [_issuer] test-discovery-doc)]+ (mt/with-dynamic-fn-redefs [oidc.discovery/discover-oidc-configuration+ (fn [_issuer] test-discovery-doc)](let [request {:auth-identity {:metadata test-config}}result (provider/authenticate :provider/oidc request)](is (= :redirect (:success? result))))))(testing "Extracts config from direct request keys"- (with-redefs [oidc.discovery/discover-oidc-configuration- (fn [_issuer] test-discovery-doc)]+ (mt/with-dynamic-fn-redefs [oidc.discovery/discover-oidc-configuration+ (fn [_issuer] test-discovery-doc)](let [request (merge test-config {:other-key "ignored"})result (provider/authenticate :provider/oidc request)](is (= :redirect (:success? result)))))))diff --git a/test/metabase/sso/providers/slack_connect_test.clj b/test/metabase/sso/providers/slack_connect_test.cljindex 2e4615d5660..48173c5c153 100644--- a/test/metabase/sso/providers/slack_connect_test.clj+++ b/test/metabase/sso/providers/slack_connect_test.clj@@ -136,20 +136,20 @@slack-connect-client-id "test-client-id"slack-connect-client-secret "test-secret"slack-connect-authentication-mode "link-only"]- (with-redefs [oidc.discovery/discover-oidc-configuration- (fn [_issuer] slack-discovery-doc)- http/post- (fn [_url _opts]- {:status 200- :body {:id_token "valid-token"- :access_token "access-token-123"}})- oidc.tokens/validate-id-token- (fn [_token _config _nonce]- {:valid? true- :claims {:sub "U12345678"- :iss "https://slack.com"- :aud "test-client-id"- :email "[email protected]"}})]+ (mt/with-dynamic-fn-redefs [oidc.discovery/discover-oidc-configuration+ (fn [_issuer] slack-discovery-doc)+ http/post+ (fn [_url _opts]+ {:status 200+ :body {:id_token "valid-token"+ :access_token "access-token-123"}})+ oidc.tokens/validate-id-token+ (fn [_token _config _nonce]+ {:valid? true+ :claims {:sub "U12345678"+ :iss "https://slack.com"+ :aud "test-client-id"+ :email "[email protected]"}})](let [request {:code "test-code":state "test-state":oidc-nonce "test-nonce"@@ -167,22 +167,22 @@slack-connect-client-id "test-client-id"slack-connect-client-secret "test-secret"slack-connect-attribute-team-id "https://slack.com/team_id"]- (with-redefs [oidc.discovery/discover-oidc-configuration- (fn [_issuer] slack-discovery-doc)- http/post- (fn [_url _opts]- {:status 200- :body {:id_token "valid-token"- :access_token "access-token-123"}})- oidc.tokens/validate-id-token- (fn [_token _config _nonce]- {:valid? true- :claims {:sub "U12345678"- :iss "https://slack.com"- :aud "test-client-id"- :email "[email protected]"- "https://slack.com/team_id" "T12345678"- :email_verified true}})]+ (mt/with-dynamic-fn-redefs [oidc.discovery/discover-oidc-configuration+ (fn [_issuer] slack-discovery-doc)+ http/post+ (fn [_url _opts]+ {:status 200+ :body {:id_token "valid-token"+ :access_token "access-token-123"}})+ oidc.tokens/validate-id-token+ (fn [_token _config _nonce]+ {:valid? true+ :claims {:sub "U12345678"+ :iss "https://slack.com"+ :aud "test-client-id"+ :email "[email protected]"+ "https://slack.com/team_id" "T12345678"+ :email_verified true}})](let [request {:code "test-code":state "test-state":oidc-nonce "test-nonce"@@ -205,25 +205,25 @@slack-connect-authentication-mode "link-only"slack-connect-user-provisioning-enabled false](mt/with-temp [:model/User user {:email "[email protected]"}]- (with-redefs [oidc.discovery/discover-oidc-configuration- (fn [_issuer] slack-discovery-doc)- oidc.state/validate-oidc-callback- (fn [_request _state _provider & _opts]- {:valid? true- :nonce "test-nonce"- :redirect "/"})- http/post- (fn [_url _opts]- {:status 200- :body {:id_token "valid-token"- :access_token "access-token-123"}})- oidc.tokens/validate-id-token- (fn [_token _config _nonce]- {:valid? true- :claims {:sub "U12345678"- :iss "https://slack.com"- :aud "test-client-id"- :email "[email protected]"}})]+ (mt/with-dynamic-fn-redefs [oidc.discovery/discover-oidc-configuration+ (fn [_issuer] slack-discovery-doc)+ oidc.state/validate-oidc-callback+ (fn [_request _state _provider & _opts]+ {:valid? true+ :nonce "test-nonce"+ :redirect "/"})+ http/post+ (fn [_url _opts]+ {:status 200+ :body {:id_token "valid-token"+ :access_token "access-token-123"}})+ oidc.tokens/validate-id-token+ (fn [_token _config _nonce]+ {:valid? true+ :claims {:sub "U12345678"+ :iss "https://slack.com"+ :aud "test-client-id"+ :email "[email protected]"}})](let [initial-session-count (t2/count :model/Session :user_id (:id user))request {:code "test-code":state "test-state"@@ -251,27 +251,27 @@slack-user-id "U_NEW_12345"];; Ensure user doesn't exist(t2/delete! :model/User :email test-email)- (with-redefs [oidc.discovery/discover-oidc-configuration- (fn [_issuer] slack-discovery-doc)- oidc.state/validate-oidc-callback- (fn [_request _state _provider & _opts]- {:valid? true- :nonce "test-nonce"- :redirect "/"})- http/post- (fn [_url _opts]- {:status 200- :body {:id_token "valid-token"- :access_token "access-token-123"}})- oidc.tokens/validate-id-token- (fn [_token _config _nonce]- {:valid? true- :claims {:sub slack-user-id- :iss "https://slack.com"- :aud "test-client-id"- :email test-email- :given_name "New"- :family_name "User"}})]+ (mt/with-dynamic-fn-redefs [oidc.discovery/discover-oidc-configuration+ (fn [_issuer] slack-discovery-doc)+ oidc.state/validate-oidc-callback+ (fn [_request _state _provider & _opts]+ {:valid? true+ :nonce "test-nonce"+ :redirect "/"})+ http/post+ (fn [_url _opts]+ {:status 200+ :body {:id_token "valid-token"+ :access_token "access-token-123"}})+ oidc.tokens/validate-id-token+ (fn [_token _config _nonce]+ {:valid? true+ :claims {:sub slack-user-id+ :iss "https://slack.com"+ :aud "test-client-id"+ :email test-email+ :given_name "New"+ :family_name "User"}})](try(let [request {:code "test-code":state "test-state"@@ -305,25 +305,25 @@:last_name "User"}];; Ensure no AuthIdentity exists for this user(t2/delete! :model/AuthIdentity :user_id (:id user) :provider "slack-connect")- (with-redefs [oidc.discovery/discover-oidc-configuration- (fn [_issuer] slack-discovery-doc)- oidc.state/validate-oidc-callback- (fn [_request _state _provider & _opts]- {:valid? true- :nonce "test-nonce"- :redirect "/"})- http/post- (fn [_url _opts]- {:status 200- :body {:id_token "valid-token"- :access_token "access-token-123"}})- oidc.tokens/validate-id-token- (fn [_token _config _nonce]- {:valid? true- :claims {:sub slack-user-id- :iss "https://slack.com"- :aud "test-client-id"- :email "[email protected]"}})]+ (mt/with-dynamic-fn-redefs [oidc.discovery/discover-oidc-configuration+ (fn [_issuer] slack-discovery-doc)+ oidc.state/validate-oidc-callback+ (fn [_request _state _provider & _opts]+ {:valid? true+ :nonce "test-nonce"+ :redirect "/"})+ http/post+ (fn [_url _opts]+ {:status 200+ :body {:id_token "valid-token"+ :access_token "access-token-123"}})+ oidc.tokens/validate-id-token+ (fn [_token _config _nonce]+ {:valid? true+ :claims {:sub slack-user-id+ :iss "https://slack.com"+ :aud "test-client-id"+ :email "[email protected]"}})](let [request {:code "test-code":state "test-state":redirect-uri "https://metabase.example.com/auth/sso/slack-connect/callback"@@ -351,25 +351,25 @@:last_name "User"}];; Ensure no AuthIdentity exists for this user(t2/delete! :model/AuthIdentity :user_id (:id user) :provider "slack-connect")- (with-redefs [oidc.discovery/discover-oidc-configuration- (fn [_issuer] slack-discovery-doc)- oidc.state/validate-oidc-callback- (fn [_request _state _provider & _opts]- {:valid? true- :nonce "test-nonce"- :redirect "/"})- http/post- (fn [_url _opts]- {:status 200- :body {:id_token "valid-token"- :access_token "access-token-123"}})- oidc.tokens/validate-id-token- (fn [_token _config _nonce]- {:valid? true- :claims {:sub slack-user-id- :iss "https://slack.com"- :aud "test-client-id"- :email "[email protected]"}})]+ (mt/with-dynamic-fn-redefs [oidc.discovery/discover-oidc-configuration+ (fn [_issuer] slack-discovery-doc)+ oidc.state/validate-oidc-callback+ (fn [_request _state _provider & _opts]+ {:valid? true+ :nonce "test-nonce"+ :redirect "/"})+ http/post+ (fn [_url _opts]+ {:status 200+ :body {:id_token "valid-token"+ :access_token "access-token-123"}})+ oidc.tokens/validate-id-token+ (fn [_token _config _nonce]+ {:valid? true+ :claims {:sub slack-user-id+ :iss "https://slack.com"+ :aud "test-client-id"+ :email "[email protected]"}})](let [initial-session-count (t2/count :model/Session :user_id (:id user))request {:code "test-code":state "test-state"diff --git a/test/metabase/sso/settings_test.clj b/test/metabase/sso/settings_test.cljindex 010feccdbd1..614aa0dce4c 100644--- a/test/metabase/sso/settings_test.clj+++ b/test/metabase/sso/settings_test.clj@@ -10,11 +10,11 @@(ldap.test/with-ldap-server!(testing "`ldap-enabled` setting validates currently saved LDAP settings"(mt/with-temporary-setting-values [ldap-enabled false]- (with-redefs [ldap/test-current-ldap-details (constantly {:status :ERROR :message "test error"})]+ (mt/with-dynamic-fn-redefs [ldap/test-current-ldap-details (constantly {:status :ERROR :message "test error"})](is (thrown-with-msg? clojure.lang.ExceptionInfo#"Unable to connect to LDAP server"(sso.settings/ldap-enabled! true))))- (with-redefs [ldap/test-current-ldap-details (constantly {:status :SUCCESS})]+ (mt/with-dynamic-fn-redefs [ldap/test-current-ldap-details (constantly {:status :SUCCESS})](sso.settings/ldap-enabled! true)(is (sso.settings/ldap-enabled))diff --git a/test/metabase/sync/analyze/classify_test.clj b/test/metabase/sync/analyze/classify_test.cljindex f41873d3b9a..27cb033fdf2 100644--- a/test/metabase/sync/analyze/classify_test.clj+++ b/test/metabase/sync/analyze/classify_test.clj@@ -217,8 +217,8 @@:fingerprint_version i/*latest-fingerprint-version*:last_analyzed nil}]- (with-redefs [classifiers.no-preview-display/infer-no-preview-display- (fn [field _] (assoc field :preview_display false))]+ (mt/with-dynamic-fn-redefs [classifiers.no-preview-display/infer-no-preview-display+ (fn [field _] (assoc field :preview_display false))](classify/classify-fields! table))(let [updated-field (t2/select-one :model/Field :id (u/the-id field))]diff --git a/test/metabase/sync/analyze/fingerprint_test.clj b/test/metabase/sync/analyze/fingerprint_test.cljindex 145b7163faf..b99a30b29e9 100644--- a/test/metabase/sync/analyze/fingerprint_test.clj+++ b/test/metabase/sync/analyze/fingerprint_test.clj@@ -148,10 +148,10 @@(defn- field-was-fingerprinted?! [fingerprint-versions field-properties](let [fingerprinted? (atom false)](binding [i/*fingerprint-version->types-that-should-be-re-fingerprinted* fingerprint-versions]- (with-redefs [qp/process-query (fn process-query- [_query rff]- (transduce identity (rff :metadata) [[1] [2] [3] [4] [5]]))- sync.fingerprint/save-fingerprint! (fn [& _] (reset! fingerprinted? true))]+ (mt/with-dynamic-fn-redefs [qp/process-query (fn process-query+ [_query rff]+ (transduce identity (rff :metadata) [[1] [2] [3] [4] [5]]))+ sync.fingerprint/save-fingerprint! (fn [& _] (reset! fingerprinted? true))](mt/with-temp [:model/Table table {}:model/Field _ (assoc field-properties :table_id (u/the-id table))][(sync.fingerprint/fingerprint-table! table)@@ -266,6 +266,7 @@:fingerprint_version 1:last_analyzed #t "2017-08-09T00:00:00"}](binding [i/*latest-fingerprint-version* 3]+ ;; fingerprinters/fingerprinter is a multimethod, so we can't use with-dynamic-fn-redefs(with-redefs [qp/process-query (fn [_query rff](transduce identity (rff :metadata) [[1] [2] [3] [4] [5]]))fingerprinters/fingerprinter (constantly (fingerprinters/constant-fingerprinter {:experimental {:fake-fingerprint? true}}))]diff --git a/test/metabase/sync/analyze_test.clj b/test/metabase/sync/analyze_test.cljindex 892f69414ca..d5ef1b165b3 100644--- a/test/metabase/sync/analyze_test.clj+++ b/test/metabase/sync/analyze_test.clj@@ -232,7 +232,7 @@(deftest analyze-unhidden-tables-test(testing "un-hiding a table should cause it to be analyzed"- (with-redefs [quick-task/submit-task! (fn [task] (task))]+ (mt/with-dynamic-fn-redefs [quick-task/submit-task! (fn [task] (task))](mt/with-temp [:model/Table table (fake-table):model/Field field (fake-field table)](set-table-visibility-type-via-api! table "hidden")diff --git a/test/metabase/sync/api/notify_test.clj b/test/metabase/sync/api/notify_test.cljindex c661b0580a0..a703b228dd9 100644--- a/test/metabase/sync/api/notify_test.clj+++ b/test/metabase/sync/api/notify_test.clj@@ -76,28 +76,28 @@payload)))))](testing "sync just table when table is provided"(let [long-sync-called? (promise), short-sync-called? (promise)]- (with-redefs [sync/sync-table! (fn [_table] (deliver long-sync-called? true))- metabase.sync.sync-metadata/sync-table-metadata! (fn [_table] (deliver short-sync-called? true))]+ (mt/with-dynamic-fn-redefs [sync/sync-table! (fn [_table] (deliver long-sync-called? true))+ metabase.sync.sync-metadata/sync-table-metadata! (fn [_table] (deliver short-sync-called? true))](post {:scan :full, :table_name table-name})(is @long-sync-called?)(is (not (realized? short-sync-called?))))))(testing "only a quick sync when quick parameter is provided"(let [long-sync-called? (promise), short-sync-called? (promise)]- (with-redefs [sync/sync-table! (fn [_table] (deliver long-sync-called? true))- metabase.sync.sync-metadata/sync-table-metadata! (fn [_table] (deliver short-sync-called? true))]+ (mt/with-dynamic-fn-redefs [sync/sync-table! (fn [_table] (deliver long-sync-called? true))+ metabase.sync.sync-metadata/sync-table-metadata! (fn [_table] (deliver short-sync-called? true))](post {:scan :schema, :table_name table-name})(is (not (realized? long-sync-called?)))(is @short-sync-called?))))(testing "full db sync by default"(let [full-sync? (promise)]- (with-redefs [sync/sync-database! (fn [_db] (deliver full-sync? true))]+ (mt/with-dynamic-fn-redefs [sync/sync-database! (fn [_db] (deliver full-sync? true))](post {})(is @full-sync?))))(testing "simple sync with params"(let [full-sync? (promise)smaller-sync (promise)]- (with-redefs [sync/sync-database! (fn [_db] (deliver full-sync? true))- metabase.sync.sync-metadata/sync-db-metadata! (fn [_db] (deliver smaller-sync true))]+ (mt/with-dynamic-fn-redefs [sync/sync-database! (fn [_db] (deliver full-sync? true))+ metabase.sync.sync-metadata/sync-db-metadata! (fn [_db] (deliver smaller-sync true))](post {:scan :schema})(is (not (realized? full-sync?)))(is @smaller-sync))))diff --git a/test/metabase/sync/field_values_test.clj b/test/metabase/sync/field_values_test.cljindex 4ec474258b0..31e68117892 100644--- a/test/metabase/sync/field_values_test.clj+++ b/test/metabase/sync/field_values_test.clj@@ -299,7 +299,7 @@;; Manually activate Field values since they are not created during sync (#53387)(field-values/get-or-create-full-field-values! (t2/select-one :model/Field (mt/id :blueberries_consumed :str)));; we throw ConnectException, which is a non-recoverable exception- (with-redefs [field-values/create-or-update-full-field-values! (fn [& _] (throw (java.net.ConnectException.)))]+ (mt/with-dynamic-fn-redefs [field-values/create-or-update-full-field-values! (fn [& _] (throw (java.net.ConnectException.)))](is (=?{:steps [["delete-expired-advanced-field-values" {}]["update-field-values" {:throwable #(instance? Exception %)}]]}diff --git a/test/metabase/sync/sync_metadata/fields/sync_metadata_test.clj b/test/metabase/sync/sync_metadata/fields/sync_metadata_test.cljindex 2c0eec530f3..afc468aab04 100644--- a/test/metabase/sync/sync_metadata/fields/sync_metadata_test.clj+++ b/test/metabase/sync/sync_metadata/fields/sync_metadata_test.clj@@ -20,9 +20,9 @@(seq db-settings) (assoc :settings db-settings)):model/Table table (assoc table :db_id (u/the-id db))](let [update-operations (atom [])]- (with-redefs [t2/update! (fn [model id updates]- (swap! update-operations conj [(name model) id updates])- (count updates))]+ (mt/with-dynamic-fn-redefs [t2/update! (fn [model id updates]+ (swap! update-operations conj [(name model) id updates])+ (count updates))](#'sync-metadata/update-field-metadata-if-needed!dbtablediff --git a/test/metabase/sync/sync_metadata/fields_test.clj b/test/metabase/sync/sync_metadata/fields_test.cljindex d75eb79fbcc..e6175e4679c 100644--- a/test/metabase/sync/sync_metadata/fields_test.clj+++ b/test/metabase/sync/sync_metadata/fields_test.clj@@ -413,12 +413,12 @@;; 3. sync the metadata for each table(if (= "for entire DB" message)(let [tables-updated (atom nil)- original-set-initial-table-sync-complete-for-db! sync-util/set-initial-table-sync-complete-for-db!]- (with-redefs [sync-util/set-initial-table-sync-complete-for-db!- (fn [& args]- (let [r (apply original-set-initial-table-sync-complete-for-db! args)]- (reset! tables-updated r)- r))]+ original-set-initial-table-sync-complete-for-db! (mt/original-fn #'sync-util/set-initial-table-sync-complete-for-db!)]+ (mt/with-dynamic-fn-redefs [sync-util/set-initial-table-sync-complete-for-db!+ (fn [& args]+ (let [r (apply original-set-initial-table-sync-complete-for-db! args)]+ (reset! tables-updated r)+ r))](sync-fields-and-fks!)(testing "Correct number fo tables updated by set-initial-table-sync-complete-for-db! in batches"(is (= 2 @tables-updated)))))diff --git a/test/metabase/sync/util_test.clj b/test/metabase/sync/util_test.cljindex affb6139da6..15a250c87d5 100644--- a/test/metabase/sync/util_test.clj+++ b/test/metabase/sync/util_test.clj@@ -66,15 +66,15 @@[f](let [step-info-atom (atom [])created-task-history-ids (atom [])- orig-log-fn @#'sync-util/log-sync-summary- origin-update-th! @#'task-history/update-task-history!]- (with-redefs [sync-util/log-sync-summary (fn [operation database operation-metadata]- (swap! step-info-atom conj operation-metadata)- (orig-log-fn operation database operation-metadata))-- task-history/update-task-history! (fn [th-id startime-ms info]- (swap! created-task-history-ids conj th-id)- (origin-update-th! th-id startime-ms info))]+ orig-log-fn (mt/original-fn #'sync-util/log-sync-summary)+ origin-update-th! (mt/original-fn #'task-history/update-task-history!)]+ (mt/with-dynamic-fn-redefs [sync-util/log-sync-summary (fn [operation database operation-metadata]+ (swap! step-info-atom conj operation-metadata)+ (orig-log-fn operation database operation-metadata))++ task-history/update-task-history! (fn [th-id startime-ms info]+ (swap! created-task-history-ids conj th-id)+ (origin-update-th! th-id startime-ms info))](f)){:operation-results @step-info-atom:task-history-ids @created-task-history-ids}))@@ -319,10 +319,10 @@(testing "If a non-recoverable error occurs during sync, `initial-sync-status` on the database is set to `aborted`"(let [_ (t2/update! :model/Database (mt/id) {:initial_sync_status "incomplete"})db (t2/select-one :model/Database :id (mt/id))]- (with-redefs [sync-metadata/make-sync-steps (fn [_]- [(sync-util/create-sync-step- "fake-step"- (fn [_] (throw (java.net.ConnectException.))))])]+ (mt/with-dynamic-fn-redefs [sync-metadata/make-sync-steps (fn [_]+ [(sync-util/create-sync-step+ "fake-step"+ (fn [_] (throw (java.net.ConnectException.))))])](sync/sync-database! db)(is (= "aborted" (t2/select-one-fn :initial_sync_status :model/Database :id (:id db)))))))@@ -345,10 +345,10 @@(t2/update! :model/Table (:id inactive-table) {:initial_sync_status "complete" :active false})(let [syncing-chan (a/chan)completed-chan (a/chan)]- (let [sync-fields! sync-fields/sync-fields!]- (with-redefs [sync-fields/sync-fields! (fn [database]- (a/>!! syncing-chan ::syncing)- (sync-fields! database))]+ (let [sync-fields! (mt/original-fn #'sync-fields/sync-fields!)]+ (mt/with-dynamic-fn-redefs [sync-fields/sync-fields! (fn [database]+ (a/>!! syncing-chan ::syncing)+ (sync-fields! database))](future(sync/sync-database! (mt/db))(a/>!! completed-chan ::sync-completed))diff --git a/test/metabase/task_history/models/task_run_test.clj b/test/metabase/task_history/models/task_run_test.cljindex 7f1758ac030..ac47bcc5ee5 100644--- a/test/metabase/task_history/models/task_run_test.clj+++ b/test/metabase/task_history/models/task_run_test.clj@@ -123,7 +123,7 @@(let [run-id (task-run/create-task-run! {:run_type :sync:entity_type :database:entity_id 1})]- (with-redefs [task-run/current-run-id (constantly run-id)]+ (mt/with-dynamic-fn-redefs [task-run/current-run-id (constantly run-id)](task-history/with-task-history {:task "t1"} :ok)(task-history/with-task-history {:task "t2"} :ok))(task-history/complete-task-run! run-id)@@ -133,7 +133,7 @@(let [run-id (task-run/create-task-run! {:run_type :sync:entity_type :database:entity_id 1})]- (with-redefs [task-run/current-run-id (constantly run-id)]+ (mt/with-dynamic-fn-redefs [task-run/current-run-id (constantly run-id)](task-history/with-task-history {:task "t1"} :ok)(try(task-history/with-task-history {:task "t2"}@@ -148,14 +148,14 @@(let [run-id (task-run/create-task-run! {:run_type :sync:entity_type :database:entity_id 1})]- (with-redefs [task-run/current-run-id (constantly run-id)]+ (mt/with-dynamic-fn-redefs [task-run/current-run-id (constantly run-id)](task-history/with-task-history {:task "t1"} :ok));; First completion(task-history/complete-task-run! run-id)(let [first-ended-at (:ended_at (t2/select-one :model/TaskRun :id run-id))](is (= :success (:status (t2/select-one :model/TaskRun :id run-id))));; Add a failing task and try to complete again- (with-redefs [task-run/current-run-id (constantly run-id)]+ (mt/with-dynamic-fn-redefs [task-run/current-run-id (constantly run-id)](try(task-history/with-task-history {:task "t2"}(throw (Exception. "fail")))diff --git a/test/metabase/test/util.clj b/test/metabase/test/util.cljindex b20da3df72d..0d1b772ea75 100644--- a/test/metabase/test/util.clj+++ b/test/metabase/test/util.clj@@ -37,6 +37,7 @@[metabase.test.data :as data][metabase.test.fixtures :as fixtures][metabase.test.initialize :as initialize]+ [metabase.test.util.dynamic-redefs :as dynamic-redefs][metabase.test.util.log][metabase.timeline.models.timeline-event :as timeline-event][metabase.util :as u]@@ -552,7 +553,7 @@(if raw-setting?(upsert-raw-setting! original-value setting-k value);; bypass the feature check when setting up mock data- (with-redefs [metabase.settings.models.setting/has-feature? (constantly true)]+ (dynamic-redefs/with-dynamic-fn-redefs [metabase.settings.models.setting/has-feature? (constantly true)](setting/set! setting-k value :bypass-read-only? true)))(catch Throwable e(throw (ex-info (str "Error in with-temporary-setting-values: " (ex-message e))@@ -567,7 +568,7 @@(if raw-setting?(restore-raw-setting! original-value setting-k);; bypass the feature check when reset settings to the original value- (with-redefs [metabase.settings.models.setting/has-feature? (constantly true)]+ (dynamic-redefs/with-dynamic-fn-redefs [metabase.settings.models.setting/has-feature? (constantly true)](setting/set! setting-k original-value :bypass-read-only? true)))(catch Throwable e(throw (ex-info (str "Error restoring original Setting value: " (ex-message e))@@ -772,10 +773,10 @@(assert (not (qs/started? temp-scheduler))"temp in-memory scheduler already started: did you use it elsewhere without shutting it down?")(binding [task.impl/*quartz-scheduler* (atom temp-scheduler)]- (with-redefs [qs/initialize (constantly temp-scheduler)- ;; prevent shutting down scheduler during thunk because some custom migration shutdown scheduler- ;; after it's done, but we need the scheduler for testing- qs/shutdown (constantly nil)]+ (dynamic-redefs/with-dynamic-fn-redefs [qs/initialize (constantly temp-scheduler)+ ;; prevent shutting down scheduler during thunk because some custom migration shutdown scheduler+ ;; after it's done, but we need the scheduler for testing+ qs/shutdown (constantly nil)](thunk)))(finally(qs/shutdown temp-scheduler))))))diff --git a/test/metabase/test/util/dynamic_redefs.clj b/test/metabase/test/util/dynamic_redefs.cljindex 17a445699e3..d49283f7610 100644--- a/test/metabase/test/util/dynamic_redefs.clj+++ b/test/metabase/test/util/dynamic_redefs.clj@@ -1,6 +1,6 @@(ns metabase.test.util.dynamic-redefs(:import- (clojure.lang Var)))+ (clojure.lang MultiFn Var)))(set! *warn-on-reflection* true)@@ -8,6 +8,16 @@"A thread-local mapping from vars to their most recently bound definition."{})+(def ^:private ^:dynamic *proxy-depths*+ "Thread-local map from redefined var to current recursion depth through its proxy.+ Used to detect capture bugs that would otherwise manifest as StackOverflowError."+ {})++(def ^:private max-proxy-depth+ "If a single var's proxy is re-entered this many times on one thread, assume a capture bug.+ Generous enough to permit deliberate recursion, low enough to fail fast before SOE."+ 128)+(defn dynamic-value"Get the value of this var that is in scope. It is the unpatched version if there is no override."[a-var]@@ -22,14 +32,33 @@(or (::original (meta a-var)) @a-var))(defn- var->proxy- "Build a proxy function to intercept the given var. The proxy checks the current scope for what to call."+ "Build a proxy function to intercept the given var. The proxy checks the current scope for what to call.+ Uses unconditional throws (not `assert`) so the safety checks fire even when `*assert*` is false.++ Accepts any `IFn` root value — keywords and collections work via their `IFn` impl+ (`(:a {:a 1})` → `1`, `({:a 1} :a)` → `1`), so the proxy's `apply` delegates correctly."[a-var]- (assert (ifn? @a-var) "Cannot proxy non-functions")- (assert (not (keyword? @a-var)) "Cannot proxy keywords")- (assert (not (coll? @a-var)) "Cannot proxy collections")+ (let [v @a-var]+ (when-not (ifn? v)+ (throw (ex-info (str "Cannot proxy non-IFn values: " a-var) {:var a-var, :value v})))+ (when (instance? MultiFn v)+ (throw (ex-info (str "Cannot proxy multimethods: " a-var ". "+ "with-dynamic-fn-redefs replaces the var's root with a proxy, which breaks "+ "dispatch and pollutes the JVM for other tests. Use defmethod (or add-method) "+ "with a dedicated test dispatch value instead.")+ {:var a-var}))))(fn [& args]- (let [current-f (dynamic-value a-var)]- (apply current-f args))))+ (let [depth (get *proxy-depths* a-var 0)]+ (when (> depth max-proxy-depth)+ (throw (ex-info (str "with-dynamic-fn-redefs: runaway recursion through proxy for " a-var ". "+ "This usually means the replacement fn calls the redefined var directly "+ "(closing over the var resolves to the proxy, not the original). "+ "Use (metabase.test.util.dynamic-redefs/original-fn " (pr-str a-var) ") "+ "to capture the unpatched function.")+ {:var a-var, :depth depth})))+ (binding [*proxy-depths* (assoc *proxy-depths* a-var (inc depth))]+ (let [current-f (dynamic-value a-var)]+ (apply current-f args))))))(defn patch-vars!"Rebind the given vars with proxies that wrap the original functions."@@ -54,7 +83,18 @@(defmacro with-dynamic-fn-redefs"A thread-safe version of with-redefs. It only supports functions, and adds a fair amount of overhead.It works by replacing each original definition with a proxy the first time it is redefined.- This proxy uses a dynamic mapping to check whether the function is currently redefined."+ This proxy uses a dynamic mapping to check whether the function is currently redefined.++ Limitations:+ - `IFn`-valued vars only. Keywords and collections are fine (they're `IFn`); multimethods+ and plain non-`IFn` value defs will throw.+ - If the replacement calls the redefined var (to delegate to the original), capture it+ via [[original-fn]] rather than `@#'the-var` or a bare symbol reference — the latter+ resolve to the proxy itself once installed, causing runaway recursion.+ - Only threads that inherit the calling thread's dynamic bindings see the replacement.+ `future`, `core.async/go`, and `core.async/thread` convey bindings automatically; raw+ `Thread`, quartz/cron workers, and unwrapped `ExecutorService` tasks do not. For those+ keep `with-redefs` — the root swap is visible to every thread."[bindings & body](let [var->definition (bindings->var->definition bindings)]`(dodiff --git a/test/metabase/test/util/i18n.clj b/test/metabase/test/util/i18n.cljindex adcbe01fee3..f81976baa4e 100644--- a/test/metabase/test/util/i18n.clj+++ b/test/metabase/test/util/i18n.clj@@ -1,6 +1,7 @@(ns metabase.test.util.i18n(:require[clojure.test :as t]+ [metabase.test.util.dynamic-redefs :as dynamic-redefs][metabase.util.i18n :as i18n][metabase.util.i18n.impl :as i18n.impl]))@@ -9,7 +10,7 @@(t/testing (format "\nwith mock i18n bundles %s\n" (pr-str bundles))(let [locale->bundle (into {} (for [[locale-name bundle] bundles][(i18n/locale locale-name) bundle]))]- (with-redefs [i18n.impl/translations (comp locale->bundle i18n/locale)]+ (dynamic-redefs/with-dynamic-fn-redefs [i18n.impl/translations (comp locale->bundle i18n/locale)](thunk)))))(defmacro with-mock-i18n-bundles!diff --git a/test/metabase/test/util_test.clj b/test/metabase/test/util_test.cljindex d3d160d5a18..3c5d29e9141 100644--- a/test/metabase/test/util_test.clj+++ b/test/metabase/test/util_test.clj@@ -109,24 +109,33 @@(def also-accidentally-a-function [:wut-up])-(deftest ^:parallel with-dynamic-fn-redefs-non-function- (testing "It is an error to redefine a non-function"+(deftest ^:parallel with-dynamic-fn-redefs-non-ifn-test+ (testing "Redefining a non-IFn value (e.g. a number) is an error — the proxy can't apply it"(is (thrown-with-msg?- AssertionError- #"Cannot proxy non-functions"+ clojure.lang.ExceptionInfo+ #"Cannot proxy non-IFn values"(mt/with-dynamic-fn-redefs [not-a-function 5]- (is (= 5 not-a-function))))))- (testing "Redefining keywords or collections is likely to surprise you, so we don't allow it"+ (is (= 5 not-a-function)))))))++(deftest ^:parallel with-dynamic-fn-redefs-keyword-and-coll-test+ (testing "Keyword-valued vars are IFn and can be redefined"+ (mt/with-dynamic-fn-redefs [accidentally-a-function :other]+ (is (= 2 (accidentally-a-function {:other 2})))))+ (testing "Collection-valued vars are IFn and can be redefined"+ (mt/with-dynamic-fn-redefs [also-accidentally-a-function [:other]]+ (is (= :other (also-accidentally-a-function 0))))))++(defmulti a-multimethod {:arglists '([x])} class)+(defmethod a-multimethod String [_] :string)+(defmethod a-multimethod Long [_] :long)++(deftest ^:parallel with-dynamic-fn-redefs-multimethod-test+ (testing "Cannot proxy a multimethod — patching its root would pollute dispatch for other threads"(is (thrown-with-msg?- AssertionError- #"Cannot proxy keywords"- (mt/with-dynamic-fn-redefs [accidentally-a-function :not-much]- (is (= :not-much accidentally-a-function)))))- (is (thrown-with-msg?- AssertionError- #"Cannot proxy collections"- (mt/with-dynamic-fn-redefs [also-accidentally-a-function #{:butter-cup}]- (is (= [:butter-cup] also-accidentally-a-function)))))))+ clojure.lang.ExceptionInfo+ #"Cannot proxy multimethods"+ (mt/with-dynamic-fn-redefs [a-multimethod (constantly :redefined)]+ (a-multimethod "hi"))))))(defn mock-me-inner []:mock/original)@@ -144,6 +153,29 @@(mock-me-outer)))(is (= :mock/redefined (z))))+(defn capture-bug-target [x] (inc x))++(defn counting-target [x]+ (if (pos? x) (counting-target (dec x)) :done))++(deftest ^:parallel with-dynamic-fn-redefs-capture-bug-test+ (testing "A replacement that delegates through the var itself is caught as runaway recursion"+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"runaway recursion through proxy"+ (mt/with-dynamic-fn-redefs [capture-bug-target (fn [x] (capture-bug-target (inc x)))]+ (capture-bug-target 0)))))+ (testing "The suggested fix — capture via original-fn — works"+ (let [orig (mt/original-fn #'capture-bug-target)]+ (mt/with-dynamic-fn-redefs [capture-bug-target (fn [x] (orig (inc x)))]+ (is (= 3 (capture-bug-target 1)))))))++(deftest ^:parallel with-dynamic-fn-redefs-deliberate-recursion-test+ (testing "Deliberate recursion through the redefined var works up to the depth threshold"+ (mt/with-dynamic-fn-redefs [counting-target (fn [x]+ (if (pos? x) (counting-target (dec x)) :recursed))]+ (is (= :recursed (counting-target 50))))))+(deftest ^:parallel ordered-subset?-test(is (mt/ordered-subset? [1 2 3] [1 2 3]))(is (mt/ordered-subset? [1 2 3] [1 2 1 3 4 5]))diff --git a/test/metabase/transforms/util_test.clj b/test/metabase/transforms/util_test.cljindex fdba39d33dd..8ece83794e9 100644--- a/test/metabase/transforms/util_test.clj+++ b/test/metabase/transforms/util_test.clj@@ -379,16 +379,18 @@;; Mock execute-base! to return success without actually running a query,;; run-cancelable-transform! to bypass schema creation / cancellation infra,;; and sync-target! to skip driver calls but still return the target table- ;; so complete-execution! can set transform_id on it.- (mt/with-dynamic-fn-redefs- [transforms-base.i/execute-base! (constantly {:status :succeeded})- transforms-base.u/sync-target! (fn [_target _database]- (t2/select-one :model/Table table-id))- transforms.u/run-cancelable-transform! (fn [_run-id _transform _driver _details run-fn & _opts]- (run-fn (a/promise-chan) nil))]- (transforms.execute/execute! transform {:run-method :manual})- (is (= transform-id- (t2/select-one-fn :transform_id :model/Table :id table-id))))))))))+ ;; so complete-execution! can set transform_id on it. execute-base! is a multimethod,+ ;; so it needs with-redefs (with-dynamic-fn-redefs refuses to proxy multimethods);+ ;; the plain fns go through with-dynamic-fn-redefs to keep them thread-local.+ (with-redefs [transforms-base.i/execute-base! (constantly {:status :succeeded})]+ (mt/with-dynamic-fn-redefs+ [transforms-base.u/sync-target! (fn [_target _database]+ (t2/select-one :model/Table table-id))+ transforms.u/run-cancelable-transform! (fn [_run-id _transform _driver _details run-fn & _opts]+ (run-fn (a/promise-chan) nil))]+ (transforms.execute/execute! transform {:run-method :manual})+ (is (= transform-id+ (t2/select-one-fn :transform_id :model/Table :id table-id)))))))))))(deftest transform-hydration-test(testing "hydrating :transform on a table"diff --git a/test/metabase/upload/impl_test.clj b/test/metabase/upload/impl_test.cljindex a7720ff30a4..238aa8dc43c 100644--- a/test/metabase/upload/impl_test.clj+++ b/test/metabase/upload/impl_test.clj@@ -449,7 +449,7 @@(test-names-match table "Some File Prefix"))))))(testing "Unicode characters are preserved in the display name, even when the table name is slugified"(let [csv-file-prefix "出色的"]- (with-redefs [upload/strictly-monotonic-now (constantly #t "2024-06-28T00:00:00")]+ (mt/with-dynamic-fn-redefs [upload/strictly-monotonic-now (constantly #t "2024-06-28T00:00:00")](do-with-uploaded-example-csv!{:csv-file-prefix csv-file-prefix}(fn [model]@@ -721,29 +721,30 @@(mt/test-drivers (mt/normal-drivers-with-feature :uploads)(when (driver/upload-type->database-type driver/*driver* :metabase.upload/offset-datetime)(with-mysql-local-infile-on-and-off- (with-redefs [driver/db-default-timezone (constantly "Z")- upload.db/current-database (constantly (mt/db))]- (let [transpose (fn [m] (apply mapv vector m))- [csv-strs expected] (transpose [["2022-01-01T12:00:00-07" "2022-01-01T19:00:00Z"]- ["2022-01-01T12:00:00-07:00" "2022-01-01T19:00:00Z"]- ["2022-01-01T12:00:00-07:30" "2022-01-01T19:30:00Z"]- ["2022-01-01T12:00:00Z" "2022-01-01T12:00:00Z"]- ["2022-01-01T12:00:00-00:00" "2022-01-01T12:00:00Z"]- ["2022-01-01T12:00:00+07" "2022-01-01T05:00:00Z"]- ["2022-01-01T12:00:00+07:00" "2022-01-01T05:00:00Z"]- ["2022-01-01T12:00:00+07:30" "2022-01-01T04:30:00Z"]- ["2022-01-01T12:00:00+0730" "2022-01-01T04:30:00Z"]])]- (testing "Fields exists after sync"- (with-upload-table!- [table (create-from-csv-and-sync-with-defaults!- :file (csv-file-with (into ["offset_datetime"] csv-strs)))]- (testing "Check the offset datetime column the correct base_type"- (is (=? :type/DateTimeWithLocalTZ- (t2/select-one-fn :base_type :model/Field :%lower.name "offset_datetime" :table_id (:id table)))))- (let [position (column-position table "offset_datetime")- values (map #(nth % position) (rows-for-table table))]- (is (= expected- values))))))))))))+ ;; driver/db-default-timezone is a multimethod, so it needs with-redefs+ (with-redefs [driver/db-default-timezone (constantly "Z")]+ (mt/with-dynamic-fn-redefs [upload.db/current-database (constantly (mt/db))]+ (let [transpose (fn [m] (apply mapv vector m))+ [csv-strs expected] (transpose [["2022-01-01T12:00:00-07" "2022-01-01T19:00:00Z"]+ ["2022-01-01T12:00:00-07:00" "2022-01-01T19:00:00Z"]+ ["2022-01-01T12:00:00-07:30" "2022-01-01T19:30:00Z"]+ ["2022-01-01T12:00:00Z" "2022-01-01T12:00:00Z"]+ ["2022-01-01T12:00:00-00:00" "2022-01-01T12:00:00Z"]+ ["2022-01-01T12:00:00+07" "2022-01-01T05:00:00Z"]+ ["2022-01-01T12:00:00+07:00" "2022-01-01T05:00:00Z"]+ ["2022-01-01T12:00:00+07:30" "2022-01-01T04:30:00Z"]+ ["2022-01-01T12:00:00+0730" "2022-01-01T04:30:00Z"]])]+ (testing "Fields exists after sync"+ (with-upload-table!+ [table (create-from-csv-and-sync-with-defaults!+ :file (csv-file-with (into ["offset_datetime"] csv-strs)))]+ (testing "Check the offset datetime column the correct base_type"+ (is (=? :type/DateTimeWithLocalTZ+ (t2/select-one-fn :base_type :model/Field :%lower.name "offset_datetime" :table_id (:id table)))))+ (let [position (column-position table "offset_datetime")+ values (map #(nth % position) (rows-for-table table))]+ (is (= expected+ values)))))))))))))(deftest create-from-csv-boolean-test(testing "Upload a CSV file"@@ -963,11 +964,11 @@(mt/test-drivers (mt/normal-drivers-with-feature :uploads);; There aren't any officially supported databases yet that don't support `:upload-with-auto-pk`;; So we'll fake it here to test it for 3rd party drivers- (let [original-supports?-fn driver.u/supports?]- (with-redefs [driver.u/supports? (fn [driver feature db]- (if (= feature :upload-with-auto-pk)- false- (original-supports?-fn driver feature db)))]+ (let [original-supports?-fn (mt/original-fn #'driver.u/supports?)]+ (mt/with-dynamic-fn-redefs [driver.u/supports? (fn [driver feature db]+ (if (= feature :upload-with-auto-pk)+ false+ (original-supports?-fn driver feature db)))](with-mysql-local-infile-on-and-off(testing "Upload a CSV file with column names that are reserved by the DB, NOT ignoring them"(testing "A single column whose name normalizes to _mb_row_id"@@ -1620,30 +1621,31 @@(with-mysql-local-infile-on-and-off(mt/with-report-timezone-id! "UTC"(testing "Append should succeed for all possible CSV column types"- (mt/with-dynamic-fn-redefs [driver/db-default-timezone (constantly "Z")- upload.db/current-database (constantly (mt/db))]- (with-upload-table!- [table (create-upload-table!- {:col->upload-type (columns-with-auto-pk- (ordered-map/ordered-map- :biginteger int-type- :float float-type- :text vchar-type- :boolean bool-type- :date date-type- :datetime datetime-type))- :rows [[1000000,1.0,"some_text",false,#t "2020-01-01",#t "2020-01-01T00:00:00"]]})]- (let [csv-rows ["biginteger,float,text,boolean,date,datetime"- "2000000,2.0,some_text,true,2020-02-02,2020-02-02T02:02:02"]- file (csv-file-with csv-rows)]- (is (some? (update-csv! action {:file file, :table-id (:id table)})))- (testing "Check the data was uploaded into the table correctly"- (is (= (set (updated-contents- action- [[1000000 1.0 "some_text" false "2020-01-01T00:00:00Z" "2020-01-01T00:00:00Z"]]- [[2000000 2.0 "some_text" true "2020-02-02T00:00:00Z" "2020-02-02T02:02:02Z"]]))- (set (rows-for-table table)))))- (io/delete-file file)))))))))))+ ;; driver/db-default-timezone is a multimethod, so it needs with-redefs+ (with-redefs [driver/db-default-timezone (constantly "Z")]+ (mt/with-dynamic-fn-redefs [upload.db/current-database (constantly (mt/db))]+ (with-upload-table!+ [table (create-upload-table!+ {:col->upload-type (columns-with-auto-pk+ (ordered-map/ordered-map+ :biginteger int-type+ :float float-type+ :text vchar-type+ :boolean bool-type+ :date date-type+ :datetime datetime-type))+ :rows [[1000000,1.0,"some_text",false,#t "2020-01-01",#t "2020-01-01T00:00:00"]]})]+ (let [csv-rows ["biginteger,float,text,boolean,date,datetime"+ "2000000,2.0,some_text,true,2020-02-02,2020-02-02T02:02:02"]+ file (csv-file-with csv-rows)]+ (is (some? (update-csv! action {:file file, :table-id (:id table)})))+ (testing "Check the data was uploaded into the table correctly"+ (is (= (set (updated-contents+ action+ [[1000000 1.0 "some_text" false "2020-01-01T00:00:00Z" "2020-01-01T00:00:00Z"]]+ [[2000000 2.0 "some_text" true "2020-02-02T00:00:00Z" "2020-02-02T02:02:02Z"]]))+ (set (rows-for-table table)))))+ (io/delete-file file))))))))))))(deftest update-offset-datetime-test(mt/test-drivers (mt/normal-drivers-with-feature :uploads)@@ -1652,26 +1654,27 @@(with-mysql-local-infile-on-and-off(mt/with-report-timezone-id! "UTC"(testing "Append should succeed for offset datetime columns"- (with-redefs [driver/db-default-timezone (constantly "Z")- upload.db/current-database (constantly (mt/db))]- (with-upload-table!- [table (create-upload-table!- {:col->upload-type (columns-with-auto-pk- (ordered-map/ordered-map :offset_datetime offset-dt-type))- :rows []})]- (let [csv-rows ["offset_datetime"- "2020-02-02T02:02:02+02:00"]- file (csv-file-with csv-rows (mt/random-name))]- (is (some? (update-csv! action {:file file, :table-id (:id table)})))- (testing "Check the data was uploaded into the table correctly"- (is (= (set (updated-contents- action- []- [[(if (driver/upload-type->database-type driver/*driver* :metabase.upload/offset-datetime)- "2020-02-02T00:02:02Z"- "2020-02-02T02:02:02+02:00")]]))- (set (rows-for-table table)))))- (io/delete-file file)))))))))))+ ;; driver/db-default-timezone is a multimethod, so it needs with-redefs+ (with-redefs [driver/db-default-timezone (constantly "Z")]+ (mt/with-dynamic-fn-redefs [upload.db/current-database (constantly (mt/db))]+ (with-upload-table!+ [table (create-upload-table!+ {:col->upload-type (columns-with-auto-pk+ (ordered-map/ordered-map :offset_datetime offset-dt-type))+ :rows []})]+ (let [csv-rows ["offset_datetime"+ "2020-02-02T02:02:02+02:00"]+ file (csv-file-with csv-rows (mt/random-name))]+ (is (some? (update-csv! action {:file file, :table-id (:id table)})))+ (testing "Check the data was uploaded into the table correctly"+ (is (= (set (updated-contents+ action+ []+ [[(if (driver/upload-type->database-type driver/*driver* :metabase.upload/offset-datetime)+ "2020-02-02T00:02:02Z"+ "2020-02-02T02:02:02+02:00")]]))+ (set (rows-for-table table)))))+ (io/delete-file file))))))))))))(deftest update-no-rows-test(mt/test-drivers (mt/normal-drivers-with-feature :uploads)@@ -2590,7 +2593,7 @@expected [:%ce%b1bcd :%_a2ba0330 :%ce%b1bc_2 :%ce%b1bc_3]displays ["αbcdεf" "αbcdεfg" "αbc 2 etc" "αbc 3 xyz"]](is (= expected (#'upload/derive-column-names ::short-column-test-driver original)))- (mt/with-dynamic-fn-redefs [upload/max-bytes (constantly 10)]+ (with-redefs [upload/max-bytes (constantly 10)](is (= displays;; The whitespace linter rejects capital greek characters that look like their roman equivalents.;; This is the easiest way to work around the capitalization of alpha.@@ -2636,11 +2639,11 @@(with-uploads-enabled!(let [db-id (mt/id)write-cache-key [db-id :write-data]]- (with-redefs [driver.conn/effective-connection-type- (fn [_database]- (if (= driver.conn/*connection-type* :write-data)- :write-data- :default))]+ (mt/with-dynamic-fn-redefs [driver.conn/effective-connection-type+ (fn [_database]+ (if (= driver.conn/*connection-type* :write-data)+ :write-data+ :default))](try(sql-jdbc.conn/invalidate-pool-for-db! (mt/db))(testing "write pool does not exist before upload create"@@ -2656,11 +2659,11 @@(with-uploads-enabled!(let [db-id (mt/id)write-cache-key [db-id :write-data]]- (with-redefs [driver.conn/effective-connection-type- (fn [_database]- (if (= driver.conn/*connection-type* :write-data)- :write-data- :default))]+ (mt/with-dynamic-fn-redefs [driver.conn/effective-connection-type+ (fn [_database]+ (if (= driver.conn/*connection-type* :write-data)+ :write-data+ :default))](try(let [table (create-upload-table!)](sql-jdbc.conn/invalidate-pool-for-db! (mt/db))diff --git a/test/metabase/users/models/user_test.clj b/test/metabase/users/models/user_test.cljindex cb10cc7f333..ff3cddf04b7 100644--- a/test/metabase/users/models/user_test.clj+++ b/test/metabase/users/models/user_test.clj@@ -228,10 +228,10 @@(zipmap (map :first_name users)(map (comp group-names :group_ids) users)))))))(testing "should be the hydrate function for `:group_ids`"- (with-redefs [user/group-ids (constantly '(user/group-ids <user>))- user/add-group-ids (fn [users]- (for [user users]- (assoc user :group_ids '(user/add-group-ids <users>))))]+ (mt/with-dynamic-fn-redefs [user/group-ids (constantly '(user/group-ids <user>))+ user/add-group-ids (fn [users]+ (for [user users]+ (assoc user :group_ids '(user/add-group-ids <users>))))](testing "for a single User"(is (= '(user/add-group-ids <users>)(-> (t2/hydrate (t2/select-one :model/User :id (mt/user->id :lucky)) :group_ids)@@ -546,7 +546,7 @@(deftest add-attributes-merges-tenant-attributes-test(testing "add-attributes should merge tenant attributes"- (with-redefs [tenants/login-attributes (constantly {"tenant_attr" "tenant_value"})]+ (mt/with-dynamic-fn-redefs [tenants/login-attributes (constantly {"tenant_attr" "tenant_value"})](let [user {:login_attributes {"user_attr" "user_value"}:email "[email protected]"}result (user/add-attributes user)]@@ -557,7 +557,7 @@(deftest add-attributes-tenant-handles-nil-login-attributes-test(testing "add-attributes with tenant attributes should handle nil login_attributes"- (with-redefs [tenants/login-attributes (constantly {"tenant_attr" "tenant_value"})]+ (mt/with-dynamic-fn-redefs [tenants/login-attributes (constantly {"tenant_attr" "tenant_value"})](let [user {:email "[email protected]"}result (user/add-attributes user)](is (= {"tenant_attr" "tenant_value"}@@ -565,7 +565,7 @@(deftest add-attributes-tenant-handles-empty-login-attributes-test(testing "add-attributes with tenant attributes should handle empty login_attributes"- (with-redefs [tenants/login-attributes (constantly {"tenant_attr" "tenant_value"})]+ (mt/with-dynamic-fn-redefs [tenants/login-attributes (constantly {"tenant_attr" "tenant_value"})](let [user {:login_attributes {}:email "[email protected]"}result (user/add-attributes user)]@@ -574,7 +574,7 @@(deftest add-attributes-handles-nil-tenant-attributes-test(testing "add-attributes should handle nil tenant attributes"- (with-redefs [tenants/login-attributes (constantly nil)]+ (mt/with-dynamic-fn-redefs [tenants/login-attributes (constantly nil)](let [user {:login_attributes {"user_attr" "user_value"}:email "[email protected]"}result (user/add-attributes user)]@@ -583,7 +583,7 @@(deftest add-attributes-handles-both-nil-tenant-and-user-attributes-test(testing "add-attributes should handle both nil tenant and user attributes"- (with-redefs [tenants/login-attributes (constantly nil)]+ (mt/with-dynamic-fn-redefs [tenants/login-attributes (constantly nil)](let [user {:email "[email protected]"}result (user/add-attributes user)](is (= {}@@ -591,8 +591,8 @@(deftest add-attributes-user-overrides-tenant-test(testing "add-attributes: user attributes should override tenant attributes with same keys"- (with-redefs [tenants/login-attributes (constantly {"shared_key" "tenant_value"- "tenant_only" "tenant_val"})]+ (mt/with-dynamic-fn-redefs [tenants/login-attributes (constantly {"shared_key" "tenant_value"+ "tenant_only" "tenant_val"})](let [user {:login_attributes {"shared_key" "user_value""user_only" "user_val"}:email "[email protected]"}@@ -604,7 +604,7 @@(deftest add-attributes-tenant-preserves-user-fields-test(testing "add-attributes with tenant attributes should preserve all other user fields"- (with-redefs [tenants/login-attributes (constantly {"tenant_attr" "tenant_value"})]+ (mt/with-dynamic-fn-redefs [tenants/login-attributes (constantly {"tenant_attr" "tenant_value"})](let [user {:id 123:email "[email protected]":first_name "John"diff --git a/test/metabase/users_rest/api_test.clj b/test/metabase/users_rest/api_test.cljindex cff78b4330f..3970571e760 100644--- a/test/metabase/users_rest/api_test.clj+++ b/test/metabase/users_rest/api_test.clj@@ -108,7 +108,7 @@:last_name "Analyst":email "[email protected]":is_data_analyst true}]- (with-redefs [perms-util/sandboxed-or-impersonated-user? (constantly true)]+ (mt/with-dynamic-fn-redefs [perms-util/sandboxed-or-impersonated-user? (constantly true)](let [result (:data (mt/user-http-request analyst :get 200 "user"))](is (= ["[email protected]"](map :email result)))))))))@@ -253,7 +253,7 @@(map :email))))(testing "But returns self if the user is sandboxed"- (with-redefs [perms-util/sandboxed-or-impersonated-user? (constantly true)]+ (mt/with-dynamic-fn-redefs [perms-util/sandboxed-or-impersonated-user? (constantly true)](is (= [rasta](->> ((mt/user-http-request :rasta :get 200 "user/recipients") :data)(map :email)))))))))diff --git a/test/metabase/util/i18n/impl_test.clj b/test/metabase/util/i18n/impl_test.cljindex 2a55abf9912..3006f566041 100644--- a/test/metabase/util/i18n/impl_test.clj+++ b/test/metabase/util/i18n/impl_test.clj@@ -144,7 +144,7 @@(binding [config/*disable-setting-cache* true](is (= "en" (i18n.impl/site-locale-from-setting)));; force an infinite loop: `log/error` will access `:site-locale` recursively to log the message- (with-redefs [metabase.settings.models.setting/get-raw-value (fn [& _] (log/error "a message to log") "foo")]+ (mt/with-dynamic-fn-redefs [metabase.settings.models.setting/get-raw-value (fn [& _] (log/error "a message to log") "foo")](testing "since the encrypted string is an invalid value for a Locale, high-level functions should return nil"(is (nil? (i18n/site-locale))`i18n/site-locale)diff --git a/test/metabase/version/settings_test.clj b/test/metabase/version/settings_test.cljindex d869924e60e..37ad04a9542 100644--- a/test/metabase/version/settings_test.clj+++ b/test/metabase/version/settings_test.clj@@ -2,6 +2,7 @@(:require[clojure.test :refer :all][metabase.config.core :as config]+ [metabase.test :as mt][metabase.version.settings :as version.settings]))(def prevent? #'version.settings/prevent-upgrade?)@@ -9,7 +10,7 @@(deftest upgrade-threshold-test(testing "it is stable but changes across releases"(letfn [(threshold [version]- (with-redefs [config/current-major-version (constantly version)]+ (mt/with-dynamic-fn-redefs [config/current-major-version (constantly version)](version.settings/upgrade-threshold)))];; asserting that across 10 versions we have at leaset 5 distinct values(let [thresholds (into [] (map threshold) (range 50 60))]diff --git a/test/metabase/view_log/events/view_log_test.clj b/test/metabase/view_log/events/view_log_test.cljindex 554ef669267..6d483b027e2 100644--- a/test/metabase/view_log/events/view_log_test.clj+++ b/test/metabase/view_log/events/view_log_test.clj@@ -204,9 +204,9 @@:model/Card {card-2-id :id} {:view_count 2}:model/Table {table-id :id} {}](let [call-count (atom 0)- t2-query-orig t2/query]+ t2-query-orig (mt/original-fn #'t2/query)](testing "increment-view-counts!* update the view_count correctly"- (with-redefs [t2/query (fn [& args] (swap! call-count inc) (apply t2-query-orig args))]+ (mt/with-dynamic-fn-redefs [t2/query (fn [& args] (swap! call-count inc) (apply t2-query-orig args))](#'events.view-log/increment-view-counts!* [;; table-id : 1 views, card-id-1: 2 views, card-id 2: 2 views{:model :model/Table :id table-id}{:model :model/Card :id card-1-id}diff --git a/test/metabase/warehouse_schema_rest/api/field_test.clj b/test/metabase/warehouse_schema_rest/api/field_test.cljindex 4c82435a21c..440f67c4ea6 100644--- a/test/metabase/warehouse_schema_rest/api/field_test.clj+++ b/test/metabase/warehouse_schema_rest/api/field_test.clj@@ -216,7 +216,7 @@(testing "PUT /api/field/:id"(testing "updating coercion strategies"(testing "Refingerprints field when updated"- (with-redefs [quick-task/submit-task! (fn [task] (task))]+ (mt/with-dynamic-fn-redefs [quick-task/submit-task! (fn [task] (task))](mt/dataset integer-coerceable(sync/sync-database! (t2/select-one :model/Database :id (mt/id)))(let [field-id (mt/id :t :f)diff --git a/test/metabase/warehouse_schema_rest/api/table_test.clj b/test/metabase/warehouse_schema_rest/api/table_test.cljindex 5dfaa40b39e..82547a70546 100644--- a/test/metabase/warehouse_schema_rest/api/table_test.clj+++ b/test/metabase/warehouse_schema_rest/api/table_test.clj@@ -530,17 +530,17 @@(assoc :db_id (:id db)))](let [called (atom 0);; original is private so a var will pick up the redef'd. need contents of var before- original (var-get #'api.table/sync-unhidden-tables)]- (with-redefs [api.table/sync-unhidden-tables- (fn [unhidden]- (when (seq unhidden)- (is (= (:id table)- (:id (first unhidden)))- "Unhidden callback did not get correct tables.")- (swap! called inc)- (let [fut (original unhidden)]- (when (future? fut)- (deref fut)))))]+ original (mt/original-fn #'api.table/sync-unhidden-tables)]+ (mt/with-dynamic-fn-redefs [api.table/sync-unhidden-tables+ (fn [unhidden]+ (when (seq unhidden)+ (is (= (:id table)+ (:id (first unhidden)))+ "Unhidden callback did not get correct tables.")+ (swap! called inc)+ (let [fut (original unhidden)]+ (when (future? fut)+ (deref fut)))))](letfn [(set-visibility! [state](testing (format "Set state => %s" (pr-str state))(mt/user-http-request :crowberto :put 200 (format "table/%d" (:id table))@@ -575,7 +575,7 @@(let [unhidden-ids (atom #{})](mt/with-temp [:model/Table {id-1 :id} {}:model/Table {id-2 :id} {:visibility_type "hidden"}]- (with-redefs [api.table/sync-unhidden-tables (fn [unhidden] (reset! unhidden-ids (set (map :id unhidden))))]+ (mt/with-dynamic-fn-redefs [api.table/sync-unhidden-tables (fn [unhidden] (reset! unhidden-ids (set (map :id unhidden))))](letfn [(set-many-vis! [ids state](reset! unhidden-ids #{})(testing (format "Set visibility type => %s" (pr-str state))diff --git a/test/metabase/warehouses/models/database_test.clj b/test/metabase/warehouses/models/database_test.cljindex 3cf6ad6a7a3..35bb4596c27 100644--- a/test/metabase/warehouses/models/database_test.clj+++ b/test/metabase/warehouses/models/database_test.clj@@ -68,23 +68,24 @@(deftest check-health!-test(mt/test-drivers (mt/normal-drivers)- (with-redefs [quick-task/submit-task! (fn [task] (task))- t2/select (fn [model & args]- (if (and (= model :model/Database) (nil? args))- [(mt/db)]- (apply t2/select model args)))]- (binding [driver.settings/*allow-testing-h2-connections* true]- (testing "status gauge resets"- (mt/with-prometheus-system! [_ system]- (mt/with-temporary-setting-values [db-connection-timeout-ms 30000]- (database/check-health!)- (is (== 1.0 (mt/metric-value system :metabase-database/status {:driver driver/*driver* :healthy true :connection-type "default"})))- (database/check-health!)- (is (== 1.0 (mt/metric-value system :metabase-database/status {:driver driver/*driver* :healthy true :connection-type "default"}))))))))))+ (let [original-select (mt/original-fn #'t2/select)]+ (mt/with-dynamic-fn-redefs [quick-task/submit-task! (fn [task] (task))+ t2/select (fn [model & args]+ (if (and (= model :model/Database) (empty? args))+ [(mt/db)]+ (apply original-select model args)))]+ (binding [driver.settings/*allow-testing-h2-connections* true]+ (testing "status gauge resets"+ (mt/with-prometheus-system! [_ system]+ (mt/with-temporary-setting-values [db-connection-timeout-ms 30000]+ (database/check-health!)+ (is (== 1.0 (mt/metric-value system :metabase-database/status {:driver driver/*driver* :healthy true :connection-type "default"})))+ (database/check-health!)+ (is (== 1.0 (mt/metric-value system :metabase-database/status {:driver driver/*driver* :healthy true :connection-type "default"})))))))))))(deftest health-check-database-test(mt/test-drivers (mt/normal-drivers)- (with-redefs [quick-task/submit-task! (fn [task] (task))]+ (mt/with-dynamic-fn-redefs [quick-task/submit-task! (fn [task] (task))](binding [driver.settings/*allow-testing-h2-connections* true](testing "successes"(mt/with-prometheus-system! [_ system]@@ -136,7 +137,7 @@(mt/test-drivers (mt/normal-drivers)(when config/ee-available?(mt/with-premium-features #{:writable-connection}- (with-redefs [quick-task/submit-task! (fn [task] (task))]+ (mt/with-dynamic-fn-redefs [quick-task/submit-task! (fn [task] (task))](binding [driver.settings/*allow-testing-h2-connections* true](testing "database with write_data_details checks both connections"(mt/with-prometheus-system! [_ system]diff --git a/test/metabase/warehouses/settings_test.clj b/test/metabase/warehouses/settings_test.cljindex 4a4826ca6fb..44d31a5c514 100644--- a/test/metabase/warehouses/settings_test.clj+++ b/test/metabase/warehouses/settings_test.clj@@ -10,11 +10,11 @@(deftest cloud-gateway-ips-test(mt/with-temp-env-var-value! [mb-cloud-gateway-ips "1.2.3.4,5.6.7.8"]- (with-redefs [premium-features/is-hosted? (constantly true)]+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly true)](testing "Setting returns ips given comma delimited ips."(is (= ["1.2.3.4" "5.6.7.8"](warehouses.settings/cloud-gateway-ips)))))(testing "Setting returns nil in self-hosted environments"- (with-redefs [premium-features/is-hosted? (constantly false)]+ (mt/with-dynamic-fn-redefs [premium-features/is-hosted? (constantly false)](is (= nil (warehouses.settings/cloud-gateway-ips)))))))diff --git a/test/metabase/warehouses_rest/api_test.clj b/test/metabase/warehouses_rest/api_test.cljindex fcc2dc4a624..271389ac1e2 100644--- a/test/metabase/warehouses_rest/api_test.clj+++ b/test/metabase/warehouses_rest/api_test.clj@@ -305,10 +305,10 @@[:model/Database {db-id :id} {}:model/Table _ {:db_id db-id}](let [queries (volatile! [])- orig-query mdb/query]- (with-redefs [mdb/query (fn [hsql]- (vswap! queries conj hsql)- (orig-query hsql))]+ orig-query (mt/original-fn #'mdb/query)]+ (mt/with-dynamic-fn-redefs [mdb/query (fn [hsql]+ (vswap! queries conj hsql)+ (orig-query hsql))](mt/user-http-request :crowberto :get 200 (format "database/%d/usage_info" db-id)))(doseq [q @queries](is (empty? (find-in-clauses q))@@ -1251,7 +1251,7 @@(deftest databases-list-include-saved-questions-tables-test-6(testing "GET /api/database?saved=true&include=tables"(testing "should work when there are no DBs that support nested queries"- (with-redefs [driver.u/supports? (constantly false)]+ (mt/with-dynamic-fn-redefs [driver.u/supports? (constantly false)](is (nil? (fetch-virtual-database)))))))(deftest ^:parallel databases-list-include-saved-questions-tables-test-7@@ -1298,7 +1298,7 @@(deftest db-metadata-saved-questions-db-test-2(testing "GET /api/database/:id/metadata works for the Saved Questions 'virtual' database"(testing "\nif no eligible Saved Questions exist the endpoint should return empty tables"- (with-redefs [api.database/cards-virtual-tables (constantly [])]+ (mt/with-dynamic-fn-redefs [api.database/cards-virtual-tables (constantly [])](is (= {:name "Saved Questions":id lib.schema.id/saved-questions-virtual-database-id:features ["basic-aggregations"]@@ -1561,7 +1561,7 @@;; Submit a blocking task with a 1-second timeout so it gets cancelled quickly.;; This simulates a stuck sync (e.g., hanging JDBC connection) that exceeds;; the quick-task timeout and gets evicted.- (with-redefs [quick-task/task-timeout-ms (constantly 1000)]+ (mt/with-dynamic-fn-redefs [quick-task/task-timeout-ms (constantly 1000)](quick-task/submit-task! (fn [] (.await blocker-latch))))(try(mt/user-http-request :crowberto :post 200 (format "database/%d/sync_schema" db-id))@@ -1599,9 +1599,9 @@(mt/with-premium-features #{:audit-app}(let [update-field-values-called? (promise)](mt/with-temp [:model/Database db {:engine "h2", :details (:details (mt/db))}]- (with-redefs [sync.field-values/update-field-values! (fn [synced-db]- (when (= (u/the-id synced-db) (u/the-id db))- (deliver update-field-values-called? :sync-called)))]+ (mt/with-dynamic-fn-redefs [sync.field-values/update-field-values! (fn [synced-db]+ (when (= (u/the-id synced-db) (u/the-id db))+ (deliver update-field-values-called? :sync-called)))](snowplow-test/with-fake-snowplow-collector(mt/user-http-request :crowberto :post 200 (format "database/%d/rescan_values" (u/the-id db)))(is (= :sync-called@@ -1714,10 +1714,10 @@(let [call-count (atom 0)ssl-values (atom [])valid? (atom false)]- (with-redefs [warehouses.util/test-database-connection (fn [_ details & _]- (swap! call-count inc)- (swap! ssl-values conj (:ssl details))- (if @valid? nil {:valid false}))]+ (mt/with-dynamic-fn-redefs [warehouses.util/test-database-connection (fn [_ details & _]+ (swap! call-count inc)+ (swap! ssl-values conj (:ssl details))+ (if @valid? nil {:valid false}))](testing "with SSL enabled, do not allow non-SSL connections"(#'warehouses.util/test-connection-details "postgres" {:ssl true})(is (= 1 @call-count))@@ -2498,7 +2498,7 @@(mt/user-http-request :crowberto :get 200 (str "database/" id "/healthcheck?connection-type=write-data")))))))))(testing "connection-type passed but not configured returns 400"(mt/with-temp [:model/Database {id :id} {:details {:host "primary"}}]- (with-redefs [driver/available? (constantly true)]+ (mt/with-dynamic-fn-redefs [driver/available? (constantly true)](is (mt/user-http-request :crowberto :get 400 (str "database/" id "/healthcheck?connection-type=write-data"))))))(testing "invalid connection-type value returns 400"(mt/with-temp [:model/Database {id :id} {}]