penpot/frontend/test/frontend_tests/data/dashboard_test.cljs
Andrey Antukh 69c33c4877
♻️ Wait on signals instead of event-loop turns on frontend tests (#12986)
* ♻️ Wait on signals instead of event-loop turns

`wait-for` counted its budget in event-loop turns (50 x `setTimeout 0`,
about 54 ms idle), so a delivery that travelled through the RxJS async
scheduler could arrive after the wait gave up. It now accepts a
`:signal`: the predicate is re-checked on every emission and the wait
resolves on the event that changes the state. The ceiling (5000 ms)
only bounds failure when a signal is given, and stays a poll budget for
the waits that have nothing to listen to.

`wait-for-store` wraps the store's input stream, which notifies its
subscribers after applying the update. The five explicit `:max-ticks`
sites move to `:timeout-ms` in the same change, so the old option never
lives in a state where destructuring silently ignores it.

New `frontend-tests.helpers.async-test` pins the contract: a late
delivery resolves, a store signal resolves on the event without a poll,
an already-true predicate does not yield, a never-true predicate records
one failure within the ceiling, and a resolved wait stops listening.

AI-assisted-by: deepseek-v4.1-flash

* ♻️ Wait for the persistence requests on their own stream

The persistence tests waited for `(= N (count @requests))` by polling the
atom at every event-loop turn. The mocked transport now pushes each
request into a `requests$` subject, and those 59 waits pass it as
`:signal`, so they resolve on the request that makes the count true. The
two predicates that mix the request count with the store state merge
both signals.

The wait that flaked (`the other file's edit is sent next`, in the
rollback test) is one of these: it no longer depends on a turn budget,
and it cannot lose the delivery.

AI-assisted-by: deepseek-v4.1-flash

* ♻️ Wait for the store event in the store backed tests

153 waits whose predicate reads the store now go through
`wait-for-store`, so they resolve on the store event that changes the
state instead of polling at every event-loop turn. The count is 153, not
the 162 the plan estimated: nine of them read the store through a
helper (`fill-color`, `shape-name`, `copy-children`) rather than
`@store`. The five sites that carried an explicit ceiling drop it, since
with an event the ceiling only bounds failure.

Resolving on the event exposes the places where the poll was really a
pause for a side effect to advance:

- `tokens-source-test` emitted `unlink-file-from-library`, a watch that
  chains a second `rp/cmd!` after an async hop. The store signal fires
  before the chain runs (the event itself dissocs the library), so the
  mock scope closed in flight and the second call reached the real HTTP
  layer. The test now waits for that second call, through the mock.
- `persistence-rollback-test` drives the persistence pipeline step by
  step; two of its waits are the pause before the next emit, not an
  effect, so they keep the poll.

AI-assisted-by: deepseek-v4.1-flash

* 📚 Document the wait contract and what still polls

`mem:frontend/testing` described `wait-for` as an immediate check plus a
bounded poll. It now waits on a signal, and the ceiling only bounds
failure; `wait-for-store` and the persistence `requests$` subject are
how a wait resolves on the event that changes the state. The waits with
nothing to listen to keep the poll, and the memory names them.

The two traps that cost a red suite are recorded too: a wait that means
"the side effect advanced" has no event and keeps the poll, and a
store-state wait can close the mock scope before the flow it observes
ends, so the chain's last RPC call has to be awaited through the mock.

AI-assisted-by: deepseek-v4.1-flash

* ♻️ Give the wait wrapper a single signal

`wait-for-store` built its options with `assoc`, so it replaced the
`:signal` a caller passed. The two waits whose predicate reads both the
store and the request counter relied on a merged signal that was being
discarded; they now pass it to `wait-for` themselves, and the wrapper
takes no options. That merge was the safety net for a request counted
after the store event, and it was inert.

The helper also reports why a wait failed (ceiling, ended signal, or an
error with its cause) instead of calling all three a timeout, counts
the predicate evaluations in the late-delivery case to prove the signal
path does not poll, reads the clock through `app.common.time` in the
helper and the test, and the test's turn probe cancels its timer. The
copyright header of `helpers/async.cljs` stays as the previous commit
left it, matching the majority spelling.

AI-assisted-by: deepseek-v4.1-flash

* ♻️ Give the cycle counter a signal too

Two waits in the retry tests read the store and the `cycles` atom, which
the `slow-cycle-timer` double fills inside the persistence watch. They
passed only the store signal, so a counter change could not wake them:
the same latent race the previous commit removed from the request count.
The double now also emits each new cycle into a `cycles$` subject, and
both waits pass the merged signal to `wait-for`.

The public `wait-for` docstring names the three failure reasons, and the
message for a failed signal bounds the cause text: the exception message
when there is one, otherwise the printed value inside a try, cut at 500
characters.

AI-assisted-by: deepseek-v4.1-flash

* ♻️ Stop the error handlers flooding the test log

Four tests in `main-errors-test` run a real error handler end to end.
Those handlers print the cause with `ex/print-throwable` before
notifying, which is what a developer wants in the app; in a test it only
writes console noise. One of them replays 10,000 offline errors, so a run
carried 10,006 dumps: 190,010 of its 192,682 lines, 13.8 MB, well past
the ~4 MB where GitHub truncates a step log and takes the summary and any
failing assertion with it.

The tests stub `ex/print-throwable` with a no-op for the duration of
their mock scope. The handlers still run, the assertions do not change,
and the 10,000-error loop still proves the governor emits once. A full
run now logs 2,583 lines and 384 KB. The single block that remains comes
from the re-entrancy guard, which prints its own notice on purpose.

AI-assisted-by: deepseek-v4.1-flash

* ♻️ Silence the deliberate WASM panic in its test

`get-svg-markup` logs a WASM panic with `console.error` before returning
empty, and `get-svg-markup-swallows-wasm-errors` sends two panics through
it on purpose. That was two 35-line dumps in which the exception printed
its own `data`, `arr` and protocol masks, and it reads like a failure that
the suite is hiding.

The test replaces `(.-error js/console)` for its body and restores it in a
`finally`. The assertions and the helper stay as they are: the same
panic answered with a different stack would still show up, because only
this test silences the console.

AI-assisted-by: deepseek-v4.1-flash

* 🐛 Use real timer for wait-poll ceiling

wait-poll read the app clock (ct/now), so tests freezing that clock
never reached the deadline and hung instead of failing. Track expiry
with a real setTimeout flag, pass timeout-ms through wait-signal and
wait-for, and cover the frozen-clock case with a regression test.

AI-assisted-by: muse-spark-1.3-contributor
2026-11-13 09:18:43 +01:00

301 lines
15 KiB
Clojure

;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
;; Copyright (c) KALEIDOS SUBSIDIARY SL
(ns frontend-tests.data.dashboard-test
(:require
[app.common.uuid :as uuid]
[app.config :as cf]
[app.main.data.common :as dcm]
[app.main.data.dashboard :as dd]
[app.main.data.notifications :as ntf]
[app.main.data.persistence :as dps]
[app.main.data.team :as dtm]
[app.main.data.websocket :as dws]
[app.main.repo :as rp]
[app.main.router :as rt]
[app.util.i18n :as i18n]
[beicon.v2.core :as rx]
[cljs.test :as t :include-macros true]
[frontend-tests.helpers.async :as async]
[frontend-tests.helpers.mock :as mock]
[potok.v2.core :as ptk]))
(defn- tr-args-for-team-org-toast
"Runs handle-change-team-organization and returns recorded i18n/tr calls."
[notification organization]
(let [team-id (uuid/next)
current-url (str "https://penpot.example.com/#/dashboard/recent?team-id=" team-id)
state {:current-team-id team-id
:teams {team-id {:id team-id :name "Team-Apple"}}}
event (dcm/handle-change-team-organization
{:team {:id team-id :organization organization}
:notification notification})
tr-calls (atom [])]
(-> (mock/with-mocks*
{cf/flags (conj cf/flags :admin-console)
;; plain variadic fn: mock/stub does not cover IFn variadic dispatch
i18n/tr (fn [key & args]
(swap! tr-calls conj [key (vec args)])
(str key ":" (pr-str args)))
rp/cmd! (mock/stub
(fn [cmd params]
(if (= [:check-nitrate-sso
{:team-id team-id :url current-url}]
[cmd params])
(rx/of {:authorized true})
(rx/throw (ex-info "unexpected RPC" {:cmd cmd :params params})))))
rt/get-current-href (mock/stub (constantly current-url))}
(await (async/observe (ptk/watch event state nil)
:on-next (fn [ev]
(t/is (contains? #{::ntf/show ::dtm/fetch-teams}
(ptk/type ev)))))))
(.then (fn [_] @tr-calls))))) (t/deftest ^:async team-org-change-toast-names-team-when-joining-org
(let [tr-calls (await (tr-args-for-team-org-toast
"dashboard.team-belong-organization"
{:id (uuid/next) :name "OrgB"}))]
(t/is (= [["dashboard.team-belong-organization" ["Team-Apple" "OrgB"]]]
tr-calls))))
(t/deftest ^:async team-org-change-toast-names-team-when-leaving-org
(let [tr-calls (await (tr-args-for-team-org-toast
"dashboard.team-no-longer-belong-organization"
{:name "OrgA"}))]
(t/is (= [["dashboard.team-no-longer-belong-organization" ["Team-Apple" "OrgA"]]]
tr-calls))))
(t/deftest ^:async team-org-change-keeps-restrictions-met-of-the-same-organization
(let [team-id (uuid/next)
organization-id (uuid/next)
state {:teams {team-id {:id team-id
:organization {:id organization-id
:name "Acme"
:restrictions-met {:send-invitations false}}}}}
event (dcm/handle-change-team-organization
{:team {:id team-id
:organization {:id organization-id
:name "Acme 2"
:permissions {:send-invitations "owners"}}}
:notification nil})]
(await (mock/with-mocks*
{cf/flags (conj cf/flags :admin-console)}
(let [organization (get-in (ptk/update event state) [:teams team-id :organization])]
(t/is (= "Acme 2" (:name organization)))
(t/is (= {:send-invitations false} (:restrictions-met organization))))))))
(t/deftest ^:async team-org-change-refetches-teams-for-the-current-profile
(let [team-id (uuid/next)
state {:teams {team-id {:id team-id}}}
event (dcm/handle-change-team-organization
{:team {:id team-id :organization {:id (uuid/next) :name "Acme"}}
:notification nil})
types (atom [])]
(await (mock/with-mocks*
{cf/flags (conj cf/flags :admin-console)}
(await (async/observe (ptk/watch event state nil)
:on-next #(swap! types conj (ptk/type %))))))
(t/is (= [::dtm/fetch-teams] @types))))
(t/deftest ^:async duplicated-project-has-a-file-count-and-is-unpinned
(let [id (uuid/next)
copy-id (uuid/next)
team-id (uuid/next)
copied {:id copy-id :team-id team-id :name "Copy"}
state {:projects {id {:id id :name "Source" :count 9 :is-pinned true}}}
result (atom state)]
(await
(mock/with-mocks*
{rp/cmd! (mock/stub (fn [cmd _]
(->> (rx/of (case cmd
:duplicate-project copied
:get-project-files [{:id (uuid/next)} {:id (uuid/next)}]))
(rx/observe-on :async))))}
(await (async/observe (ptk/watch (dd/duplicate-project {:id id :name "Source"}) state (rx/empty))
:on-next #(swap! result (partial ptk/update %))))))
(t/is (= (assoc copied :count 2 :is-pinned false) (get-in @result [:projects copy-id])))))
(t/deftest moving-current-team-into-sso-organization-redirects
(t/async done
(let [team-id (uuid/next)
organization {:id (uuid/next) :name "OrgA"}
current-url (str "https://penpot.example.com/#/dashboard/recent?team-id=" team-id)
redirect-url "https://idp.example.com/authorize"
state {:current-team-id team-id}
event (dcm/handle-change-team-organization
{:team {:id team-id :organization organization}
:notification nil})]
(mock/with-mocks
{cf/flags (conj cf/flags :admin-console)
rp/cmd! (mock/stub
(fn [cmd params]
(if (= [:check-nitrate-sso
{:team-id team-id :url current-url}]
[cmd params])
(rx/of {:authorized false :redirect-uri redirect-url})
(rx/throw (ex-info "unexpected RPC" {:cmd cmd :params params})))))
rt/get-current-href (mock/stub (constantly current-url))}
(fn [done']
(->> (ptk/watch event state nil)
(rx/reduce conj [])
(rx/subs!
(fn [events]
(t/is (= [::rt/nav-raw] (mapv ptk/type events))))
(fn [error]
(t/is false (str "unexpected error: " error))
(done'))
(fn []
(done')))))
done))))
(t/deftest organization-sso-activation-redirects-current-team
(t/async done
(let [team-id (uuid/next)
organization-id (uuid/next)
current-url (str "https://penpot.example.com/#/workspace?team-id=" team-id)
redirect-url "https://idp.example.com/authorize"
state {:current-team-id team-id
:teams {team-id {:id team-id
:organization {:id organization-id}}}}
event (dcm/handle-organization-change-sso
{:organization-id organization-id})]
(mock/with-mocks
{cf/flags (conj cf/flags :admin-console)
rp/cmd! (mock/stub
(fn [cmd params]
(if (= [:check-nitrate-sso
{:team-id team-id :url current-url}]
[cmd params])
(rx/of {:authorized false :redirect-uri redirect-url})
(rx/throw (ex-info "unexpected RPC" {:cmd cmd :params params})))))
rt/get-current-href (mock/stub (constantly current-url))}
(fn [done']
(->> (ptk/watch event state nil)
(rx/reduce conj [])
(rx/subs!
(fn [events]
(t/is (= [::rt/nav-raw] (mapv ptk/type events))))
(fn [error]
(t/is false (str "unexpected error: " error))
(done'))
(fn []
(done')))))
done))))
(defn- sent-messages
"Runs the watch of `event` against `stream` with `dws/send` stubbed
and resolves to the messages it sends over the websocket."
[event state stream]
(let [sent (atom [])]
(-> (mock/with-mocks*
{dws/send (mock/stub (fn [msg] (swap! sent conj msg) msg))}
(await (async/observe (ptk/watch event state stream))))
(.then (fn [_] @sent)))))
(t/deftest ^:async dashboard-initialize-subscribes-to-team
(let [team-id (uuid/next)
state {:profile-id (uuid/next)
:teams {team-id {:id team-id :organization {:id (uuid/next)}}}}
sent (await (sent-messages (dd/initialize team-id) state (rx/empty)))]
(t/is (= [{:type :subscribe-team :team-id team-id}] sent))))
(t/deftest ^:async dashboard-initialize-resubscribes-on-reconnect
(let [team-id (uuid/next)
state {:profile-id (uuid/next)
:teams {team-id {:id team-id}}}
stream (rx/of (ptk/data-event ::dws/opened {})
(ptk/data-event ::dws/opened {}))
sent (await (sent-messages (dd/initialize team-id) state stream))]
(t/is (= 3 (count sent)))
(t/is (every? #(= {:type :subscribe-team :team-id team-id} %) sent))))
(t/deftest ^:async dashboard-initialize-accepts-team-organization-messages
(let [team-id (uuid/next)
org-id (uuid/next)
state {:profile-id (uuid/next)
:teams {team-id {:id team-id :organization {:id org-id}}}}
message (fn [topic]
(ptk/data-event ::dws/message
{:type :organization-change-sso
:topic topic
:organization-id org-id}))
stream (rx/of (message org-id) (message (uuid/next)))
processed (atom [])]
(await (mock/with-mocks*
{dws/send (mock/stub identity)}
(await (async/observe (ptk/watch (dd/initialize team-id) state stream)
:on-next #(swap! processed conj (ptk/type %))))))
(t/is (= 1 (count (filter #{::dcm/handle-organization-change-sso} @processed))))))
;; Scenario: the user duplicates a file whose workspace still has a change
;; waiting to be saved. Proves: the copy is requested once the save is done,
;; and only then is the user told, with a warning that the copy misses what
;; could not be saved, never replaced by the success toast.
(t/deftest ^:async duplicating-a-file-waits-for-its-pending-changes
(let [file-id (uuid/next)
commit-id (uuid/next)
calls (atom [])
answer (rx/subject)
store (ptk/store {:state {:files {}
:persistence {:queue (conj #queue [] commit-id)
:index {commit-id {:id commit-id :file-id file-id}}}}})]
(await
(mock/with-mocks*
{dps/force-persist-files-and-wait (mock/stub (fn [file-ids _]
(swap! calls conj [:wait file-ids])
(rx/empty)))
rp/cmd! (mock/stub (fn [cmd _]
(swap! calls conj [cmd])
(->> answer (rx/take 1) (rx/observe-on :async))))
i18n/tr (fn ([key] (str "translated:" key)) ([key & _] (str "translated:" key)))}
(ptk/emit! store (dd/duplicate-files [{:id file-id :name "File"}]))
(await (async/wait-for #(= 2 (count @calls)) "the copy is requested"))
(t/is (= [[:wait #{file-id}] [:duplicate-file]] @calls))
(t/is (nil? (:notification @store)) "nothing is told before the copy exists")
(rx/push! answer {:id (uuid/next)})
(await (async/wait-for-store store #(some? (:notification @store)) "the user is told"))
(await (async/settle))
(t/is (= "translated:dashboard.duplicate-unsaved-changes"
(get-in @store [:notification :content])))
(t/is (= :warning (get-in @store [:notification :level])))))))
;; Scenario: the user duplicates a file with everything saved. Proves: the
;; success toast shows once the copy exists, not when it is requested.
(t/deftest ^:async duplicating-a-saved-file-tells-once-the-copy-exists
(let [file-id (uuid/next)
answer (rx/subject)
sent (atom 0)
store (ptk/store {:state {:files {}}})]
(await
(mock/with-mocks*
{dps/force-persist-files-and-wait (mock/stub (fn [_ _] (rx/empty)))
rp/cmd! (mock/stub (fn [_ _]
(swap! sent inc)
(->> answer (rx/take 1) (rx/observe-on :async))))
i18n/tr (fn ([key] (str "translated:" key)) ([key & _] (str "translated:" key)))}
(ptk/emit! store (dd/duplicate-files [{:id file-id :name "File"}]))
(await (async/wait-for #(= 1 @sent) "the copy is requested"))
(t/is (nil? (:notification @store)))
(rx/push! answer {:id (uuid/next)})
(await (async/wait-for-store store #(some? (:notification @store)) "the user is told"))
(t/is (= "translated:dashboard.success-duplicate-file"
(get-in @store [:notification :content])))
(t/is (= :success (get-in @store [:notification :level])))))))
;; Scenario: the server fails to copy the file. Proves: no success toast
;; claims a copy that does not exist.
(t/deftest ^:async a-failed-copy-tells-no-success
(let [errors (atom [])
store (ptk/store {:state {:files {}}
:on-error #(swap! errors conj %)})]
(await
(mock/with-mocks*
{dps/force-persist-files-and-wait (mock/stub (fn [_ _] (rx/empty)))
rp/cmd! (mock/stub (fn [_ _]
(->> (rx/throw (ex-info "copy failed" {:type :internal}))
(rx/observe-on :async))))
i18n/tr (fn ([key] (str "translated:" key)) ([key & _] (str "translated:" key)))}
(ptk/emit! store (dd/duplicate-files [{:id (uuid/next) :name "File"}]))
(await (async/wait-for #(seq @errors) "the copy fails"))
(await (async/settle))
(t/is (nil? (:notification @store)))))))