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
Move agent API tests from enterprise to OSS (#71456)
Edward Paget655a3f6ac700
diff --git a/bin/test-agent b/bin/test-agentindex f444616446b..cc42da81477 100755--- a/bin/test-agent+++ b/bin/test-agent@@ -10,15 +10,30 @@# Usage:# bin/test-agent :only '[metabase.foo-test]'# bin/test-agent :only '[metabase.foo-test/some-test]'+# bin/test-agent --oss :only '[metabase.foo-test]' # run without EE extensions# bin/test-agent # runs all tests (rarely what you want)#-# Any extra arguments are forwarded directly to `clojure -X:dev:ee:ee-dev:test`.+# Options:+# --oss Run without enterprise extensions (uses :oss:oss-dev instead of :ee:ee-dev)+#+# Any extra arguments are forwarded directly to the clojure test command.# The :test alias uses port 0 (OS-assigned random port) so parallel runs never collide.set -euo pipefailexport HAWK_MODE=cli/ci+# Check for --oss flag+ALIASES=":dev:ee:ee-dev:test"+args=()+for arg in "$@"; do+ if [[ "$arg" == "--oss" ]]; then+ ALIASES=":dev:ci:test:oss:oss-dev"+ else+ args+=("$arg")+ fi+done+# Filter noise and strip ANSI escape sequencesclean_output() {grep -v '^Downloading: ' \@@ -28,4 +43,4 @@ clean_output() {| sed $'s/\033[\[(][0-9;]*[A-Za-z]//g; s/\033[^[]*//g'}-exec clojure -X:dev:ee:ee-dev:test "$@" 2>&1 | clean_output+exec clojure -X"${ALIASES}" "${args[@]}" 2>&1 | clean_outputdiff --git a/enterprise/backend/test/metabase_enterprise/agent_api/api_test.clj b/enterprise/backend/test/metabase_enterprise/agent_api/api_test.cljindex 81ccd5448fa..0225753f974 100644--- a/enterprise/backend/test/metabase_enterprise/agent_api/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/agent_api/api_test.clj@@ -1,60 +1,41 @@(ns metabase-enterprise.agent-api.api-test+ "Agent API tests that require enterprise features (JWT authentication, scopes)."(:require[buddy.sign.jwt :as jwt][clojure.test :refer :all]- [environ.core :as env]- [java-time.api :as t]- [medley.core :as m][metabase-enterprise.sso.test-setup :as sso.test-setup][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]- [metabase.lib.normalize :as lib.normalize]- [metabase.metabot.settings] ; for setting definitions- [metabase.metabot.tools.util :as metabot.tools.u]- [metabase.search.ingestion :as search.ingestion]- [metabase.search.test-util :as search.tu]- [metabase.session.models.session :as session.models][metabase.test :as mt][metabase.test.fixtures :as fixtures][metabase.test.http-client :as client][metabase.test.util :as tu]- [metabase.util :as u]- [metabase.util.json :as json]- [metabase.warehouse-schema.models.field-values :as field-values][toucan2.core :as t2]))(set! *warn-on-reflection* true)-(use-fixtures :once (fixtures/initialize :db :test-users))+(use-fixtures :once (fixtures/initialize :db :web-server :test-users))-(defn- current-epoch-seconds []- (int (/ (System/currentTimeMillis) 1000)))--(defn- sign-jwt- "Sign a JWT with the test secret. Automatically adds `iat` claim if not present,- which is required for max-age validation."- [claims]- (jwt/sign (merge {:iat (current-epoch-seconds)} claims) sso.test-setup/default-jwt-secret))--(defmacro with-agent-api-setup!- "Sets up JWT authentication for Agent API tests.- Reuses the SSO JWT test setup which handles premium features and settings correctly."+(defmacro ^:private with-agent-api-setup!+ "Sets up JWT authentication and premium features for Agent API tests."[& body]`(sso.test-setup/with-jwt-default-setup!(mt/with-additional-premium-features #{:agent-api :metabot-v3}~@body)))+(defn- current-epoch-seconds []+ (quot (System/currentTimeMillis) 1000))++(defn- sign-jwt [claims]+ (jwt/sign (merge {:iat (current-epoch-seconds)} claims) sso.test-setup/default-jwt-secret))+(defn- auth-headers- "Create authorization headers with a signed JWT for the given email."- ([]- (auth-headers "[email protected]"))+ ([] (auth-headers "[email protected]"))([email]{"authorization" (str "Bearer " (sign-jwt {:email email}))}))(defn- agent-client- "Helper for making authenticated agent API requests, similar to mt/user-http-request.- Takes a test user keyword (e.g. :rasta, :crowberto), method, expected status, endpoint,- and optional body for POST/PUT requests."+ "Helper for making authenticated agent API requests using JWT."[user method expected-status endpoint & [body]](let [email (:username (mt/user->credentials user))headers (auth-headers email)]@@ -121,28 +102,6 @@(client/client :get 401 "agent/v1/ping"{:request-options {:headers (auth-headers "[email protected]")}}))))))-(deftest agent-api-session-token-auth-test- (with-agent-api-setup!- (testing "Session tokens via X-Metabase-Session header authenticate successfully"- (let [session-key (session.models/generate-session-key)- _ (t2/insert! :model/Session- {:id (session.models/generate-session-id)- :user_id (mt/user->id :rasta)- :session_key session-key})- response (client/client :get 200 "agent/v1/ping"- {:request-options {:headers {"x-metabase-session" session-key}}})]- (is (= {:message "pong"} response))))-- (testing "Invalid session token returns 401"- (let [fake-session-key (str (random-uuid))- response (client/client :get 401 "agent/v1/ping"- {:request-options {:headers {"x-metabase-session" fake-session-key}}})]- ;; Invalid session means standard middleware doesn't set metabase-user-id,- ;; so our middleware sees no auth and returns missing_authorization- (is (= {:error "missing_authorization"- :message "Authentication required. Use X-Metabase-Session header or Authorization: Bearer <jwt>."}- response))))))-(deftest agent-api-inactive-user-test(with-agent-api-setup!(testing "JWT for deactivated user returns same error as invalid token (no information disclosure)"@@ -152,22 +111,6 @@(client/client :get 401 "agent/v1/ping"{:request-options {:headers (auth-headers email)}})))))))-(deftest agent-api-expired-session-test- (testing "Expired sessions are rejected by the standard session middleware"- (with-agent-api-setup!- ;; Set max-session-age to 1 minute for this test- (with-redefs [env/env (assoc env/env :max-session-age "1")]- (let [session-key (session.models/generate-session-key)- old-time (t/minus (t/instant) (t/minutes 2))]- (mt/with-temp [:model/Session _ {:user_id (mt/user->id :rasta)- :session_key session-key- :created_at old-time}]- (testing "Session older than max-session-age is rejected"- (is (= {:error "missing_authorization"- :message "Authentication required. Use X-Metabase-Session header or Authorization: Bearer <jwt>."}- (client/client :get 401 "agent/v1/ping"- {:request-options {:headers {"x-metabase-session" session-key}}}))))))))))-(deftest agent-api-user-binding-test(with-agent-api-setup!(testing "User is correctly bound from JWT - permissions are enforced"@@ -189,193 +132,6 @@(is (= "You don't have permissions to do that."(agent-client :rasta :get 403 (str "agent/v1/metric/" (:id metric)))))))))))-(deftest get-table-details-test- (with-agent-api-setup!- (testing "Returns table details for valid table ID"- (let [table-id (mt/id :orders)]- (is (=? {:type "table"- :id table-id- :name "ORDERS"- :display_name "Orders"- :database_id (mt/id)- :fields sequential?- :related_tables sequential?}- (agent-client :rasta :get 200 (str "agent/v1/table/" table-id))))))-- (testing "Returns 404 for non-existent table"- (is (= "Not found."- (agent-client :rasta :get 404 "agent/v1/table/999999"))))-- (testing "Respects query parameters"- (let [table-id (mt/id :orders)]- (is (=? {:type "table"- :id table-id- :fields empty?}- (agent-client :rasta :get 200- (str "agent/v1/table/" table-id "?with-fields=false&with-related-tables=false"))))))-- (testing "Field values are excluded by default"- (let [table-id (mt/id :orders)- table (agent-client :rasta :get 200 (str "agent/v1/table/" table-id))]- (is (every? #(nil? (:field_values %)) (:fields table)))))-- (testing "Field values are included when explicitly requested"- (let [table-id (mt/id :orders)- table (agent-client :rasta :get 200 (str "agent/v1/table/" table-id "?with-field-values=true"))]- (is (some #(seq (:field_values %)) (:fields table)))))))--(deftest get-metric-details-test- (with-agent-api-setup!- (mt/with-temp [:model/Card metric {:name "Test Metric"- :type :metric- :database_id (mt/id)- :dataset_query (orders-count-query)}]- (testing "Returns metric details for valid metric ID"- (is (=? {:type "metric"- :id (:id metric)- :name "Test Metric"- :queryable_dimensions sequential?}- (agent-client :rasta :get 200 (str "agent/v1/metric/" (:id metric))))))-- (testing "Respects query parameters"- (is (=? {:type "metric"- :id (:id metric)}- (agent-client :rasta :get 200- (str "agent/v1/metric/" (:id metric)- "?with-queryable-dimensions=false&with-field-values=false")))))-- (testing "Returns 404 for non-existent metric"- (is (= "Not found."- (agent-client :rasta :get 404 "agent/v1/metric/999999")))))))--(defn- ensure-fresh-field-values!- "Ensure field values exist for a field by deleting any existing ones and recreating them."- [field-id]- (t2/delete! :model/FieldValues :field_id field-id :type :full)- (field-values/get-or-create-full-field-values! (t2/select-one :model/Field :id field-id)))--(defn- visible-field-id- "Find the field-id string for a field by display name within a table's visible columns."- [table-id field-display-name]- (let [mp (mt/metadata-provider)- query (lib/query mp (lib.metadata/table mp table-id))- field-prefix (metabot.tools.u/table-field-id-prefix table-id)- visible-cols (lib/visible-columns query)]- (->> (keep-indexed (fn [i col]- (when (= (lib/display-name query col) field-display-name)- (str field-prefix i)))- visible-cols)- first)))--(deftest get-table-field-values-test- (with-agent-api-setup!- ;; Ensure field values exist for the field we'll test- (ensure-fresh-field-values! (mt/id :people :state))-- (testing "Returns field statistics and values with default limit of 30"- (let [table-id (mt/id :people)- field-id (visible-field-id table-id "State")]- (is (some? field-id) "Should find the State field")- (let [result (agent-client :crowberto :get 200- (format "agent/v1/table/%d/field/%s/values" table-id field-id))]- (is (=? {:value_metadata {:statistics {:distinct-count 49}- :field_values sequential?}}- result))- (is (<= (count (:values result)) 30) "Should apply default limit of 30"))))-- (testing "Respects explicit limit parameter"- (let [table-id (mt/id :people)- field-id (visible-field-id table-id "State")]- (is (=? {:value_metadata {:field_values #(= 5 (count %))}}- (agent-client :crowberto :get 200- (format "agent/v1/table/%d/field/%s/values?limit=5" table-id field-id))))))-- (testing "Returns 404 for non-existent table"- (is (= "Not found."- (agent-client :crowberto :get 404 "agent/v1/table/999999/field/t999999-0/values"))))-- (testing "Returns 400 for invalid field-id format"- (let [table-id (mt/id :people)]- (is (= "Invalid field_id format: not-a-valid-id"- (agent-client :crowberto :get 400 (format "agent/v1/table/%d/field/not-a-valid-id/values" table-id))))))))--(deftest search-test- (with-agent-api-setup!- (binding [search.ingestion/*force-sync* true]- (search.tu/with-new-search-if-available-otherwise-legacy- (mt/with-temp [:model/Table _ {:name "AgentSearchTestTable"}]- (testing "Returns search results for term queries"- (is (=? {:data [{:type "table" :name "AgentSearchTestTable"}]- :total_count 1}- (agent-client :rasta :post 200 "agent/v1/search"- {:term_queries ["AgentSearchTestTable"]})))))))))--(defn- decode-query- "Decode a base64-encoded query response to a Clojure map, then normalize it so lib functions work."- [response]- (-> response :query u/decode-base64 json/decode+kw lib.normalize/normalize))--(deftest construct-query-test- (with-agent-api-setup!- (testing "Constructs a simple query from a table"- (let [table-id (mt/id :orders)- response (agent-client :rasta :post 200 "agent/v1/construct-query"- {:table_id table-id})]- (is (string? (:query response)) "Response should contain a query string")- (let [decoded (decode-query response)]- (is (= :mbql/query (lib/normalized-query-type decoded)))- (is (= (mt/id) (lib/database-id decoded)))- (is (= (mt/id :orders) (lib/primary-source-table-id decoded))))))-- (testing "Applies default limit of 200 when no limit is specified"- (let [table-id (mt/id :orders)- response (agent-client :rasta :post 200 "agent/v1/construct-query"- {:table_id table-id})- decoded (decode-query response)]- (is (= 200 (lib/current-limit decoded)))))-- (testing "Respects explicit limit"- (let [table-id (mt/id :orders)- response (agent-client :rasta :post 200 "agent/v1/construct-query"- {:table_id table-id- :limit 10})- decoded (decode-query response)]- (is (= 10 (lib/current-limit decoded)))))-- (testing "Returns 404 for non-existent table"- (is (= "No table found with table_id 999999"- (agent-client :rasta :post 404 "agent/v1/construct-query"- {:table_id 999999}))))))--(deftest execute-query-test- (with-agent-api-setup!- (testing "Executes a query and returns results with column metadata"- (let [table-id (mt/id :orders)- construct-resp (agent-client :rasta :post 200 "agent/v1/construct-query"- {:table_id table-id- :limit 5})- ;; Streaming response returns 202 (accepted) since it starts streaming before completion- execute-resp (agent-client :rasta :post 202 "agent/v1/execute"- {:query (:query construct-resp)})]- (is (=? {:status "completed"- :row_count 5- :data {:cols (fn [cols]- (and (seq cols)- (every? :name cols)- (every? :base_type cols)))- :rows (fn [rows] (= 5 (count rows)))}}- execute-resp))))-- (testing "Enforces agent query row limit even when query specifies a higher limit"- (let [table-id (mt/id :orders)- construct-resp (agent-client :rasta :post 200 "agent/v1/construct-query"- {:table_id table-id- :limit 300})- execute-resp (agent-client :rasta :post 202 "agent/v1/execute"- {:query (:query construct-resp)})]- (is (=? {:status "completed" :row_count 200}- execute-resp))))))-(deftest execute-query-records-query-execution-test(with-agent-api-setup!(testing "Executed queries are recorded with :agent context"@@ -393,111 +149,6 @@(t2/select-one :model/QueryExecution :executor_id user-id))](is (= :agent (:context query-execution))))))))-(deftest get-metric-field-values-test- (with-agent-api-setup!- (ensure-fresh-field-values! (mt/id :orders :quantity))- (mt/with-temp [:model/Card metric {:name "Test Metric"- :type :metric- :database_id (mt/id)- :dataset_query (orders-count-query)}]- (testing "Returns field statistics for a field that has statistics"- (let [metric-details (agent-client :rasta :get 200 (str "agent/v1/metric/" (:id metric)))- quantity-field (m/find-first #(= (:name %) "QUANTITY") (:queryable_dimensions metric-details))]- (is (some? quantity-field) "Quantity field should be in queryable_dimensions")- (when-let [field-id (:field_id quantity-field)]- (is (=? {:value_metadata {:statistics map?- :field_values sequential?}}- (agent-client :rasta :get 200- (format "agent/v1/metric/%d/field/%s/values" (:id metric) field-id)))))))-- (testing "Returns 404 for non-existent metric"- (is (= "Not found."- (agent-client :rasta :get 404 "agent/v1/metric/999999/field/c999999-0/values"))))-- (testing "Returns 400 for field-id from wrong entity type"- ;; Using a table field-id (t-prefix) when querying a metric should fail- (is (re-find #"does not match expected prefix"- (agent-client :rasta :get 400 (format "agent/v1/metric/%d/field/t123-0/values" (:id metric)))))))))--(deftest construct-metric-query-test- (with-agent-api-setup!- (mt/with-temp [:model/Card metric {:name "Test Metric"- :type :metric- :database_id (mt/id)- :dataset_query (orders-count-query)}]- (testing "Constructs a query from a metric"- (let [response (agent-client :rasta :post 200 "agent/v1/construct-query"- {:metric_id (:id metric)})]- (is (string? (:query response)) "Response should contain a query string")- (let [decoded (decode-query response)]- (is (= :mbql/query (lib/normalized-query-type decoded)))- (is (= (mt/id) (lib/database-id decoded))))))-- (testing "Returns 404 for non-existent metric"- (is (= "Not found."- (agent-client :rasta :post 404 "agent/v1/construct-query"- {:metric_id 999999})))))))--(deftest construct-query-with-count-aggregation-test- (with-agent-api-setup!- (testing "Count aggregation without field_id produces a valid query"- (let [table-id (mt/id :orders)- response (agent-client :rasta :post 200 "agent/v1/construct-query"- {:table_id table-id- :aggregations [{:function "count"}]- :limit 10})]- (is (string? (:query response)))- (let [decoded (decode-query response)]- (is (= 1 (count (lib/aggregations decoded)))))))-- (testing "Count aggregation with field_id still works"- (let [table-id (mt/id :orders)- table (agent-client :rasta :get 200 (str "agent/v1/table/" table-id))- field-id (-> table :fields first :field_id)- response (agent-client :rasta :post 200 "agent/v1/construct-query"- {:table_id table-id- :aggregations [{:function "count" :field_id field-id}]- :limit 10})]- (is (string? (:query response)))- (let [decoded (decode-query response)]- (is (= 1 (count (lib/aggregations decoded)))))))))--(deftest construct-query-with-filters-test- (with-agent-api-setup!- (testing "Constructs a query with filters"- (let [table-id (mt/id :orders)- ;; Get table details to find a valid field_id- table (agent-client :rasta :get 200 (str "agent/v1/table/" table-id))- field-id (-> table :fields first :field_id)- response (agent-client :rasta :post 200 "agent/v1/construct-query"- {:table_id table-id- :filters [{:field_id field-id- :operation "is-not-null"}]- :limit 10})]- (is (string? (:query response)))- (let [decoded (decode-query response)]- (is (seq (lib/filters decoded)) "Query should have filters"))))))--(deftest get-table-details-with-measures-test- (with-agent-api-setup!- (let [measure-def (-> (lib/query (mt/metadata-provider)- (lib.metadata/table (mt/metadata-provider) (mt/id :orders)))- (lib/aggregate (lib/sum (lib.metadata/field (mt/metadata-provider) (mt/id :orders :total)))))]- (mt/with-temp [:model/Measure {measure-id :id} {:name "Total Revenue"- :table_id (mt/id :orders)- :definition measure-def}]- (testing "with-measures=false (default) does not include measures"- (let [table (agent-client :rasta :get 200 (str "agent/v1/table/" (mt/id :orders)))]- (is (nil? (:measures table)))))-- (testing "with-measures=true includes measures for the table"- (let [table (agent-client :rasta :get 200- (str "agent/v1/table/" (mt/id :orders) "?with-measures=true"))]- (is (sequential? (:measures table)))- (is (=? [{:id measure-id- :name "Total Revenue"}]- (:measures table)))))))))-(deftest agent-api-scope-enforcement-test(with-agent-api-setup!(let [table-id (mt/id :orders)]@@ -547,69 +198,6 @@(client/client :get 403 (str "agent/v1/table/" table-id){:request-options {:headers headers}}))))))))-(deftest combined-query-test- (with-agent-api-setup!- (testing "Returns results for a table query"- (let [table-id (mt/id :orders)- field-id (visible-field-id table-id "ID")- response (agent-client :rasta :post 202 "agent/v1/query"- {:table_id table-id- :order_by [{:field {:field_id field-id} :direction "asc"}]- :limit 5})]- (is (=? {:status "completed"- :row_count 5- :continuation_token string?- :data {:cols sequential?- :rows (fn [rows] (= 5 (count rows)))}}- response))))-- (testing "Continuation token returns next page of results"- (let [table-id (mt/id :orders)- field-id (visible-field-id table-id "ID")- page1 (agent-client :rasta :post 202 "agent/v1/query"- {:table_id table-id- :order_by [{:field {:field_id field-id} :direction "asc"}]- :limit 5})- page2 (agent-client :rasta :post 202 "agent/v1/query"- {:continuation_token (:continuation_token page1)})]- (is (=? {:row_count 5- :continuation_token string?- :data {:rows (fn [rows] (= 5 (count rows)))}}- page1))- (is (=? {:row_count 5- :continuation_token string?- :data {:rows (fn [rows] (= 5 (count rows)))}}- page2))- (is (not= (get-in page1 [:data :rows])- (get-in page2 [:data :rows]))- "Pages should return different rows")))-- (testing "No continuation_token when all rows are returned"- (is (=? {:status "completed"- :continuation_token nil?}- (agent-client :rasta :post 202 "agent/v1/query"- {:table_id (mt/id :orders)- :aggregations [{:function "count"}]}))))-- (testing "Constraint cap limits results to 200 rows"- (is (=? {:status "completed"- :row_count (fn [n] (<= n 200))}- (agent-client :rasta :post 202 "agent/v1/query"- {:table_id (mt/id :orders)- :limit 1000}))))))--(deftest combined-query-metric-test- (with-agent-api-setup!- (mt/with-temp [:model/Card metric {:name "Test Metric"- :type :metric- :database_id (mt/id)- :dataset_query (orders-count-query)}]- (testing "Returns results for a metric query"- (is (=? {:status "completed"- :row_count pos?}- (agent-client :rasta :post 202 "agent/v1/query"- {:metric_id (:id metric)})))))))-(deftest combined-query-scope-test(with-agent-api-setup!(testing "agent:query scope grants access to combined query endpoint"@@ -636,17 +224,3 @@(client/client :post 403 "agent/v1/query"{:request-options {:headers headers}}{:table_id (mt/id :orders) :limit 1})))))))--(deftest search-finds-metrics-test- (with-agent-api-setup!- (binding [search.ingestion/*force-sync* true]- (search.tu/with-new-search-if-available-otherwise-legacy- (mt/with-temp [:model/Card _metric {:name "AgentSearchTestMetric"- :type :metric- :database_id (mt/id)- :dataset_query (orders-count-query)}]- (testing "Returns metrics in search results"- (is (=? {:data [{:type "metric" :name "AgentSearchTestMetric"}]- :total_count 1}- (agent-client :rasta :post 200 "agent/v1/search"- {:term_queries ["AgentSearchTestMetric"]})))))))))diff --git a/test/metabase/agent_api/api_test.clj b/test/metabase/agent_api/api_test.cljnew file mode 100644index 00000000000..f4f8eef28ed--- /dev/null+++ b/test/metabase/agent_api/api_test.clj@@ -0,0 +1,428 @@+(ns metabase.agent-api.api-test+ "Agent API functional tests using session-based authentication.+ JWT and scope-related tests live in metabase-enterprise.agent-api.api-test."+ (:require+ [clojure.test :refer :all]+ [environ.core :as env]+ [java-time.api :as t]+ [medley.core :as m]+ [metabase.lib.core :as lib]+ [metabase.lib.metadata :as lib.metadata]+ [metabase.lib.normalize :as lib.normalize]+ [metabase.metabot.tools.util :as metabot.tools.u]+ [metabase.search.ingestion :as search.ingestion]+ [metabase.search.test-util :as search.tu]+ [metabase.session.models.session :as session.models]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [metabase.test.http-client :as client]+ [metabase.util :as u]+ [metabase.util.json :as json]+ [metabase.warehouse-schema.models.field-values :as field-values]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(use-fixtures :once (fixtures/initialize :db :web-server :test-users))++(defn- orders-count-query+ "Create a simple count query on the orders table using lib functions."+ []+ (-> (lib/query (mt/metadata-provider)+ (lib.metadata/table (mt/metadata-provider) (mt/id :orders)))+ (lib/aggregate (lib/count))))++;;; ------------------------------------------------- Session Auth Tests ------------------------------------------------++(deftest agent-api-session-token-auth-test+ (testing "Session tokens via X-Metabase-Session header authenticate successfully"+ (let [session-key (session.models/generate-session-key)+ _ (t2/insert! :model/Session+ {:id (session.models/generate-session-id)+ :user_id (mt/user->id :rasta)+ :session_key session-key})+ response (client/client :get 200 "agent/v1/ping"+ {:request-options {:headers {"x-metabase-session" session-key}}})]+ (is (= {:message "pong"} response))))++ (testing "Invalid session token returns 401"+ (let [fake-session-key (str (random-uuid))+ response (client/client :get 401 "agent/v1/ping"+ {:request-options {:headers {"x-metabase-session" fake-session-key}}})]+ ;; Invalid session means standard middleware doesn't set metabase-user-id,+ ;; so our middleware sees no auth and returns missing_authorization+ (is (= {:error "missing_authorization"+ :message "Authentication required. Use X-Metabase-Session header or Authorization: Bearer <jwt>."}+ response)))))++(deftest agent-api-expired-session-test+ (testing "Expired sessions are rejected by the standard session middleware"+ ;; Set max-session-age to 1 minute for this test+ (with-redefs [env/env (assoc env/env :max-session-age "1")]+ (let [session-key (session.models/generate-session-key)+ old-time (t/minus (t/instant) (t/minutes 2))]+ (mt/with-temp [:model/Session _ {:user_id (mt/user->id :rasta)+ :session_key session-key+ :created_at old-time}]+ (testing "Session older than max-session-age is rejected"+ (is (= {:error "missing_authorization"+ :message "Authentication required. Use X-Metabase-Session header or Authorization: Bearer <jwt>."}+ (client/client :get 401 "agent/v1/ping"+ {:request-options {:headers {"x-metabase-session" session-key}}})))))))))++;;; ------------------------------------------------- Functional Tests --------------------------------------------------++(deftest get-table-details-test+ (testing "Returns table details for valid table ID"+ (let [table-id (mt/id :orders)]+ (is (=? {:type "table"+ :id table-id+ :name "ORDERS"+ :display_name "Orders"+ :database_id (mt/id)+ :fields sequential?+ :related_tables sequential?}+ (mt/user-http-request :rasta :get 200 (str "agent/v1/table/" table-id))))))++ (testing "Returns 404 for non-existent table"+ (is (= "Not found."+ (mt/user-http-request :rasta :get 404 "agent/v1/table/999999"))))++ (testing "Respects query parameters"+ (let [table-id (mt/id :orders)]+ (is (=? {:type "table"+ :id table-id+ :fields empty?}+ (mt/user-http-request :rasta :get 200+ (str "agent/v1/table/" table-id "?with-fields=false&with-related-tables=false"))))))++ (testing "Field values are excluded by default"+ (let [table-id (mt/id :orders)+ table (mt/user-http-request :rasta :get 200 (str "agent/v1/table/" table-id))]+ (is (every? #(nil? (:field_values %)) (:fields table)))))++ (testing "Field values are included when explicitly requested"+ (let [table-id (mt/id :orders)+ table (mt/user-http-request :rasta :get 200 (str "agent/v1/table/" table-id "?with-field-values=true"))]+ (is (some #(seq (:field_values %)) (:fields table))))))++(deftest get-metric-details-test+ (mt/with-temp [:model/Card metric {:name "Test Metric"+ :type :metric+ :database_id (mt/id)+ :dataset_query (orders-count-query)}]+ (testing "Returns metric details for valid metric ID"+ (is (=? {:type "metric"+ :id (:id metric)+ :name "Test Metric"+ :queryable_dimensions sequential?}+ (mt/user-http-request :rasta :get 200 (str "agent/v1/metric/" (:id metric))))))++ (testing "Respects query parameters"+ (is (=? {:type "metric"+ :id (:id metric)}+ (mt/user-http-request :rasta :get 200+ (str "agent/v1/metric/" (:id metric)+ "?with-queryable-dimensions=false&with-field-values=false")))))++ (testing "Returns 404 for non-existent metric"+ (is (= "Not found."+ (mt/user-http-request :rasta :get 404 "agent/v1/metric/999999"))))))++(defn- ensure-fresh-field-values!+ "Ensure field values exist for a field by deleting any existing ones and recreating them."+ [field-id]+ (t2/delete! :model/FieldValues :field_id field-id :type :full)+ (field-values/get-or-create-full-field-values! (t2/select-one :model/Field :id field-id)))++(defn- visible-field-id+ "Find the field-id string for a field by display name within a table's visible columns."+ [table-id field-display-name]+ (let [mp (mt/metadata-provider)+ query (lib/query mp (lib.metadata/table mp table-id))+ field-prefix (metabot.tools.u/table-field-id-prefix table-id)+ visible-cols (lib/visible-columns query)]+ (->> (keep-indexed (fn [i col]+ (when (= (lib/display-name query col) field-display-name)+ (str field-prefix i)))+ visible-cols)+ first)))++(deftest get-table-field-values-test+ ;; Ensure field values exist for the field we'll test+ (ensure-fresh-field-values! (mt/id :people :state))++ (testing "Returns field statistics and values with default limit of 30"+ (let [table-id (mt/id :people)+ field-id (visible-field-id table-id "State")]+ (is (some? field-id) "Should find the State field")+ (let [result (mt/user-http-request :crowberto :get 200+ (format "agent/v1/table/%d/field/%s/values" table-id field-id))]+ (is (=? {:value_metadata {:statistics {:distinct-count 49}+ :field_values sequential?}}+ result))+ (is (<= (count (:values result)) 30) "Should apply default limit of 30"))))++ (testing "Respects explicit limit parameter"+ (let [table-id (mt/id :people)+ field-id (visible-field-id table-id "State")]+ (is (=? {:value_metadata {:field_values #(= 5 (count %))}}+ (mt/user-http-request :crowberto :get 200+ (format "agent/v1/table/%d/field/%s/values?limit=5" table-id field-id))))))++ (testing "Returns 404 for non-existent table"+ (is (= "Not found."+ (mt/user-http-request :crowberto :get 404 "agent/v1/table/999999/field/t999999-0/values"))))++ (testing "Returns 400 for invalid field-id format"+ (let [table-id (mt/id :people)]+ (is (= "Invalid field_id format: not-a-valid-id"+ (mt/user-http-request :crowberto :get 400 (format "agent/v1/table/%d/field/not-a-valid-id/values" table-id)))))))++(deftest search-test+ (binding [search.ingestion/*force-sync* true]+ (search.tu/with-new-search-if-available-otherwise-legacy+ (mt/with-temp [:model/Table _ {:name "AgentSearchTestTable"}]+ (testing "Returns search results for term queries"+ (is (=? {:data [{:type "table" :name "AgentSearchTestTable"}]+ :total_count 1}+ (mt/user-http-request :rasta :post 200 "agent/v1/search"+ {:term_queries ["AgentSearchTestTable"]}))))))))++(defn- decode-query+ "Decode a base64-encoded query response to a Clojure map, then normalize it so lib functions work."+ [response]+ (-> response :query u/decode-base64 json/decode+kw lib.normalize/normalize))++(deftest construct-query-test+ (testing "Constructs a simple query from a table"+ (let [table-id (mt/id :orders)+ response (mt/user-http-request :rasta :post 200 "agent/v1/construct-query"+ {:table_id table-id})]+ (is (string? (:query response)) "Response should contain a query string")+ (let [decoded (decode-query response)]+ (is (= :mbql/query (lib/normalized-query-type decoded)))+ (is (= (mt/id) (lib/database-id decoded)))+ (is (= (mt/id :orders) (lib/primary-source-table-id decoded))))))++ (testing "Applies default limit of 200 when no limit is specified"+ (let [table-id (mt/id :orders)+ response (mt/user-http-request :rasta :post 200 "agent/v1/construct-query"+ {:table_id table-id})+ decoded (decode-query response)]+ (is (= 200 (lib/current-limit decoded)))))++ (testing "Respects explicit limit"+ (let [table-id (mt/id :orders)+ response (mt/user-http-request :rasta :post 200 "agent/v1/construct-query"+ {:table_id table-id+ :limit 10})+ decoded (decode-query response)]+ (is (= 10 (lib/current-limit decoded)))))++ (testing "Returns 404 for non-existent table"+ (is (= "No table found with table_id 999999"+ (mt/user-http-request :rasta :post 404 "agent/v1/construct-query"+ {:table_id 999999})))))++(deftest execute-query-test+ (testing "Executes a query and returns results with column metadata"+ (let [table-id (mt/id :orders)+ construct-resp (mt/user-http-request :rasta :post 200 "agent/v1/construct-query"+ {:table_id table-id+ :limit 5})+ ;; Streaming response returns 202 (accepted) since it starts streaming before completion+ execute-resp (mt/user-http-request :rasta :post 202 "agent/v1/execute"+ {:query (:query construct-resp)})]+ (is (=? {:status "completed"+ :row_count 5+ :data {:cols (fn [cols]+ (and (seq cols)+ (every? :name cols)+ (every? :base_type cols)))+ :rows (fn [rows] (= 5 (count rows)))}}+ execute-resp))))++ (testing "Enforces agent query row limit even when query specifies a higher limit"+ (let [table-id (mt/id :orders)+ construct-resp (mt/user-http-request :rasta :post 200 "agent/v1/construct-query"+ {:table_id table-id+ :limit 300})+ execute-resp (mt/user-http-request :rasta :post 202 "agent/v1/execute"+ {:query (:query construct-resp)})]+ (is (=? {:status "completed" :row_count 200}+ execute-resp)))))++(deftest get-metric-field-values-test+ (ensure-fresh-field-values! (mt/id :orders :quantity))+ (mt/with-temp [:model/Card metric {:name "Test Metric"+ :type :metric+ :database_id (mt/id)+ :dataset_query (orders-count-query)}]+ (testing "Returns field statistics for a field that has statistics"+ (let [metric-details (mt/user-http-request :rasta :get 200 (str "agent/v1/metric/" (:id metric)))+ quantity-field (m/find-first #(= (:name %) "QUANTITY") (:queryable_dimensions metric-details))]+ (is (some? quantity-field) "Quantity field should be in queryable_dimensions")+ (when-let [field-id (:field_id quantity-field)]+ (is (=? {:value_metadata {:statistics map?+ :field_values sequential?}}+ (mt/user-http-request :rasta :get 200+ (format "agent/v1/metric/%d/field/%s/values" (:id metric) field-id)))))))++ (testing "Returns 404 for non-existent metric"+ (is (= "Not found."+ (mt/user-http-request :rasta :get 404 "agent/v1/metric/999999/field/c999999-0/values"))))++ (testing "Returns 400 for field-id from wrong entity type"+ ;; Using a table field-id (t-prefix) when querying a metric should fail+ (is (re-find #"does not match expected prefix"+ (mt/user-http-request :rasta :get 400 (format "agent/v1/metric/%d/field/t123-0/values" (:id metric))))))))++(deftest construct-metric-query-test+ (mt/with-temp [:model/Card metric {:name "Test Metric"+ :type :metric+ :database_id (mt/id)+ :dataset_query (orders-count-query)}]+ (testing "Constructs a query from a metric"+ (let [response (mt/user-http-request :rasta :post 200 "agent/v1/construct-query"+ {:metric_id (:id metric)})]+ (is (string? (:query response)) "Response should contain a query string")+ (let [decoded (decode-query response)]+ (is (= :mbql/query (lib/normalized-query-type decoded)))+ (is (= (mt/id) (lib/database-id decoded))))))++ (testing "Returns 404 for non-existent metric"+ (is (= "Not found."+ (mt/user-http-request :rasta :post 404 "agent/v1/construct-query"+ {:metric_id 999999}))))))++(deftest construct-query-with-count-aggregation-test+ (testing "Count aggregation without field_id produces a valid query"+ (let [table-id (mt/id :orders)+ response (mt/user-http-request :rasta :post 200 "agent/v1/construct-query"+ {:table_id table-id+ :aggregations [{:function "count"}]+ :limit 10})]+ (is (string? (:query response)))+ (let [decoded (decode-query response)]+ (is (= 1 (count (lib/aggregations decoded)))))))++ (testing "Count aggregation with field_id still works"+ (let [table-id (mt/id :orders)+ table (mt/user-http-request :rasta :get 200 (str "agent/v1/table/" table-id))+ field-id (-> table :fields first :field_id)+ response (mt/user-http-request :rasta :post 200 "agent/v1/construct-query"+ {:table_id table-id+ :aggregations [{:function "count" :field_id field-id}]+ :limit 10})]+ (is (string? (:query response)))+ (let [decoded (decode-query response)]+ (is (= 1 (count (lib/aggregations decoded))))))))++(deftest construct-query-with-filters-test+ (testing "Constructs a query with filters"+ (let [table-id (mt/id :orders)+ ;; Get table details to find a valid field_id+ table (mt/user-http-request :rasta :get 200 (str "agent/v1/table/" table-id))+ field-id (-> table :fields first :field_id)+ response (mt/user-http-request :rasta :post 200 "agent/v1/construct-query"+ {:table_id table-id+ :filters [{:field_id field-id+ :operation "is-not-null"}]+ :limit 10})]+ (is (string? (:query response)))+ (let [decoded (decode-query response)]+ (is (seq (lib/filters decoded)) "Query should have filters")))))++(deftest get-table-details-with-measures-test+ (let [measure-def (-> (lib/query (mt/metadata-provider)+ (lib.metadata/table (mt/metadata-provider) (mt/id :orders)))+ (lib/aggregate (lib/sum (lib.metadata/field (mt/metadata-provider) (mt/id :orders :total)))))]+ (mt/with-temp [:model/Measure {measure-id :id} {:name "Total Revenue"+ :table_id (mt/id :orders)+ :definition measure-def}]+ (testing "with-measures=false (default) does not include measures"+ (let [table (mt/user-http-request :rasta :get 200 (str "agent/v1/table/" (mt/id :orders)))]+ (is (nil? (:measures table)))))++ (testing "with-measures=true includes measures for the table"+ (let [table (mt/user-http-request :rasta :get 200+ (str "agent/v1/table/" (mt/id :orders) "?with-measures=true"))]+ (is (sequential? (:measures table)))+ (is (=? [{:id measure-id+ :name "Total Revenue"}]+ (:measures table))))))))++(deftest combined-query-test+ (testing "Returns results for a table query"+ (let [table-id (mt/id :orders)+ field-id (visible-field-id table-id "ID")+ response (mt/user-http-request :rasta :post 202 "agent/v1/query"+ {:table_id table-id+ :order_by [{:field {:field_id field-id} :direction "asc"}]+ :limit 5})]+ (is (=? {:status "completed"+ :row_count 5+ :continuation_token string?+ :data {:cols sequential?+ :rows (fn [rows] (= 5 (count rows)))}}+ response))))++ (testing "Continuation token returns next page of results"+ (let [table-id (mt/id :orders)+ field-id (visible-field-id table-id "ID")+ page1 (mt/user-http-request :rasta :post 202 "agent/v1/query"+ {:table_id table-id+ :order_by [{:field {:field_id field-id} :direction "asc"}]+ :limit 5})+ page2 (mt/user-http-request :rasta :post 202 "agent/v1/query"+ {:continuation_token (:continuation_token page1)})]+ (is (=? {:row_count 5+ :continuation_token string?+ :data {:rows (fn [rows] (= 5 (count rows)))}}+ page1))+ (is (=? {:row_count 5+ :continuation_token string?+ :data {:rows (fn [rows] (= 5 (count rows)))}}+ page2))+ (is (not= (get-in page1 [:data :rows])+ (get-in page2 [:data :rows]))+ "Pages should return different rows")))++ (testing "No continuation_token when all rows are returned"+ (is (=? {:status "completed"+ :continuation_token nil?}+ (mt/user-http-request :rasta :post 202 "agent/v1/query"+ {:table_id (mt/id :orders)+ :aggregations [{:function "count"}]}))))++ (testing "Constraint cap limits results to 200 rows"+ (is (=? {:status "completed"+ :row_count (fn [n] (<= n 200))}+ (mt/user-http-request :rasta :post 202 "agent/v1/query"+ {:table_id (mt/id :orders)+ :limit 1000})))))++(deftest combined-query-metric-test+ (mt/with-temp [:model/Card metric {:name "Test Metric"+ :type :metric+ :database_id (mt/id)+ :dataset_query (orders-count-query)}]+ (testing "Returns results for a metric query"+ (is (=? {:status "completed"+ :row_count pos?}+ (mt/user-http-request :rasta :post 202 "agent/v1/query"+ {:metric_id (:id metric)}))))))++(deftest search-finds-metrics-test+ (binding [search.ingestion/*force-sync* true]+ (search.tu/with-new-search-if-available-otherwise-legacy+ (mt/with-temp [:model/Card _metric {:name "AgentSearchTestMetric"+ :type :metric+ :database_id (mt/id)+ :dataset_query (orders-count-query)}]+ (testing "Returns metrics in search results"+ (is (=? {:data [{:type "metric" :name "AgentSearchTestMetric"}]+ :total_count 1}+ (mt/user-http-request :rasta :post 200 "agent/v1/search"+ {:term_queries ["AgentSearchTestMetric"]}))))))))diff --git a/test/metabase/agent_api/test_util.clj b/test/metabase/agent_api/test_util.cljnew file mode 100644index 00000000000..60291231351--- /dev/null+++ b/test/metabase/agent_api/test_util.clj@@ -0,0 +1,42 @@+(ns metabase.agent-api.test-util+ "Test helpers for the Agent API. Provides JWT authentication setup and+ helper functions for making authenticated requests against agent API endpoints."+ (:require+ [buddy.sign.jwt :as jwt]+ [metabase.test :as mt]+ [metabase.test.http-client :as client]+ [metabase.util.random :as u.random]))++(set! *warn-on-reflection* true)++(def default-jwt-secret+ "Default JWT secret for agent API tests. Regenerated on each test run."+ (u.random/secure-hex 32))++(def default-jwt-idp-uri "http://test.idp.metabase.com")++(defn- current-epoch-seconds []+ (quot (System/currentTimeMillis) 1000))++(defn sign-jwt+ "Sign a JWT with the test secret. Automatically adds `iat` claim if not present."+ [claims]+ (jwt/sign (merge {:iat (current-epoch-seconds)} claims) default-jwt-secret))++(defn auth-headers+ "Create authorization headers with a signed JWT for the given email."+ ([]+ (auth-headers "[email protected]"))+ ([email]+ {"authorization" (str "Bearer " (sign-jwt {:email email}))}))++(defn agent-client+ "Helper for making authenticated agent API requests.+ Takes a test user keyword (e.g. :rasta, :crowberto), method, expected status, endpoint,+ and optional body for POST/PUT requests."+ [user method expected-status endpoint & [body]]+ (let [email (:username (mt/user->credentials user))+ headers (auth-headers email)]+ (apply client/client method expected-status endpoint+ {:request-options {:headers headers}}+ (when body [body]))))diff --git a/test/metabase/analytics/stats_test.clj b/test/metabase/analytics/stats_test.cljindex 851f5f52e6b..143d75546b3 100644--- a/test/metabase/analytics/stats_test.clj+++ b/test/metabase/analytics/stats_test.clj@@ -230,11 +230,12 @@:started_at (t/offset-date-time)})(deftest new-impl-test- (mt/with-temp [:model/QueryExecution _ (merge query-execution-defaults- {:error "some error"})- :model/QueryExecution _ (merge query-execution-defaults- {:error "some error"})- :model/QueryExecution _ query-execution-defaults]+ (mt/with-temp [:model/QueryExecution {id1 :id} (merge query-execution-defaults+ {:error "some error"})+ :model/QueryExecution {id2 :id} (merge query-execution-defaults+ {:error "some error"})+ :model/QueryExecution {id3 :id} query-execution-defaults]+ (t2/delete! :model/QueryExecution :id [:not-in [id1 id2 id3]])(is (= (old-execution-metrics)(#'stats/execution-metrics))"the new version of the executions metrics works the same way the old one did")))diff --git a/test/metabase/collections_rest/api_test.clj b/test/metabase/collections_rest/api_test.cljindex 26aee8778c9..a5c00a2cbc0 100644--- a/test/metabase/collections_rest/api_test.clj+++ b/test/metabase/collections_rest/api_test.clj@@ -3398,7 +3398,7 @@(is (some #(= card-id (:id %)) items)"Card should be in collection items"))(testing "Published table should NOT appear"- (is (not (some #(= table-id (:id %)) items))+ (is (not (some #(and (= "table" (:model %)) (= table-id (:id %))) items))"Published table should NOT be in collection items in OSS"))))))(testing "In OSS (without :library feature), published tables should NOT appear in root collection items"(mt/with-premium-features #{}@@ -3406,7 +3406,7 @@:is_published true:name "Root Published Table"}](let [items (:data (mt/user-http-request :crowberto :get 200 "collection/root/items"))]- (is (not (some #(= table-id (:id %)) items))+ (is (not (some #(and (= "table" (:model %)) (= table-id (:id %))) items))"Published table should NOT be in root collection items in OSS"))))))(deftest unarchive-collection-requires-curate-perms-on-destination-test