Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Make four order- and speed-dependent tests deterministic (#5523)

David Gil8d0e4d3597cd
diff --git a/test/controllers/api/v1/transactions_controller_test.rb b/test/controllers/api/v1/transactions_controller_test.rb
index 89a1db71a4..65af6ed13e 100644
--- a/test/controllers/api/v1/transactions_controller_test.rb
+++ b/test/controllers/api/v1/transactions_controller_test.rb
@@ -1820,10 +1820,14 @@ end
{ "X-Api-Key" => api_key.display_key }
end
+ # Counts every statement, including the ones the query cache answers. The
+ # cache hides a preload whose IN list happens to match an earlier one in the
+ # same order, and that order follows the rows' physical order, so skipping
+ # cached statements made the count change from run to run. It would also
+ # hide a repeated per-row query.
def count_db_queries(&block)
queries = 0
callback = lambda do |_name, _started, _finished, _unique_id, payload|
- return if payload[:cached]
return if payload[:name].in?(%w[SCHEMA TRANSACTION])
queries += 1
diff --git a/test/models/demo/financekit_generator_test.rb b/test/models/demo/financekit_generator_test.rb
index 03bc564c2a..650c4df709 100644
--- a/test/models/demo/financekit_generator_test.rb
+++ b/test/models/demo/financekit_generator_test.rb
@@ -115,7 +115,10 @@ class Demo::FinancekitGeneratorTest < ActiveSupport::TestCase
transaction.update!(category: family.categories.find_by!(name: "Shopping"),
extra: transaction.extra.except("demo_financekit_activity_version"))
end
- source_records = item.financekit_accounts.flat_map { |mapping| mapping.financekit_transactions.pluck(:id, :entry_id, :raw_payload) }
+ # In id order: without ORDER BY Postgres returns rows in whatever order it
+ # finds them, which an update can change, so the same set came back reordered.
+ source_records = -> { FinancekitTransaction.where(financekit_account_lineage: item.financekit_account_lineages).order(:id).pluck(:id, :entry_id, :raw_payload) }
+ original_source_records = source_records.call
balances = [ card.balance, cash.balance ]
assert_difference [ "Entry.count", "Transfer.count" ], 1 do
@@ -129,7 +132,7 @@ class Demo::FinancekitGeneratorTest < ActiveSupport::TestCase
assert_equal @checking, payment.reload.entryable.transfer.from_account
assert_nil payment.entryable.category
assert_equal balances, [ card.reload.balance, cash.reload.balance ]
- assert_equal source_records, item.financekit_accounts.flat_map { |mapping| mapping.financekit_transactions.pluck(:id, :entry_id, :raw_payload) }
+ assert_equal original_source_records, source_records.call
end
test "standalone demo uses a funded synthetic checking account when demo checking is absent" do
diff --git a/test/system/chart_sidebar_resize_test.rb b/test/system/chart_sidebar_resize_test.rb
index 6abfb5431c..4b87f74244 100644
--- a/test/system/chart_sidebar_resize_test.rb
+++ b/test/system/chart_sidebar_resize_test.rb
@@ -72,36 +72,23 @@ class ChartSidebarResizeTest < ApplicationSystemTestCase
test "the chart's dates keep their shape and their place at the edges while a sidebar animates" do
assert_selector "#{NET_WORTH} svg .tick text", count: 2
page.execute_script(<<~JS)
- window.__labels = []; window.__sampling = true;
- // Measured after each frame is painted (resize observers run before the
- // paint, after requestAnimationFrame callbacks), so it sees what was shown.
- const afterPaint = (fn) => requestAnimationFrame(() => setTimeout(fn, 0));
- const sample = () => {
+ window.__labels = [];
+ window.__sample = () => {
const element = document.querySelector("#{NET_WORTH}");
const container = element.getBoundingClientRect();
const svg = element.querySelector("svg");
const [first, last] = Array.from(element.querySelectorAll("svg .tick text")).map((t) => t.getBoundingClientRect());
- // On a slow machine this can run after the next animation step has
- // begun, measuring a layout the chart has not followed yet and that was
- // never painted: only count frames where the drawing fills its container.
+ // Only frames where the drawing fills its container.
const painted = svg && Math.round(Number(svg.getAttribute("width"))) === Math.round(container.width);
if (first && last && painted) window.__labels.push([Math.round(container.width), first.left - container.left, container.right - last.right, first.width, last.width]);
- if (window.__sampling) afterPaint(sample);
};
- // The settled baseline, before the toggle; then after each paint.
- sample();
+ // The settled baseline, before the toggle.
+ window.__sample();
JS
before = net_worth_width
- toggle_left_sidebar
+ step_left_sidebar
wait_until_settled(changed_from: before)
- # The chart can settle between two samples: stop only once one at the
- # final width is in.
- final = net_worth_width
- page.document.synchronize(10) do
- last = page.evaluate_script("window.__labels.at(-1)?.[0]")
- raise Capybara::ExpectationNotMet, "no sample at the final width yet (last: #{last.inspect})" unless last == final
- end
- page.execute_script("window.__sampling = false")
+ page.execute_script("window.__sample()")
samples = page.evaluate_script("window.__labels")
widths = samples.map(&:first)
@@ -435,25 +422,21 @@ class ChartSidebarResizeTest < ApplicationSystemTestCase
wait_until_settled
page.execute_script(<<~JS)
- window.__frames = []; window.__sampling = true;
- const afterPaint = (fn) => requestAnimationFrame(() => setTimeout(fn, 0));
+ window.__frames = [];
const chart = document.querySelector("#{sankey} [data-sankey-chart-target='chart']") || document.querySelector("#{sankey}");
- const sample = () => {
+ window.__sample = () => {
const svg = chart.querySelector("svg");
const width = chart.clientWidth;
const painted = svg && Math.round(Number(svg.getAttribute("width"))) === Math.round(width);
// By datum: the subcategory's bar, whether or not its label fits.
const sub = !!svg && Array.from(svg.querySelectorAll("g > path:not(.sankey-link)")).some((bar) => bar.__data__?.name === "Sankey Groceries");
if (painted) window.__frames.push([width, sub]);
- if (window.__sampling) afterPaint(sample);
};
- sample();
JS
before = net_worth_width
- toggle_left_sidebar
+ step_left_sidebar
wait_until_settled(changed_from: before)
- sleep 0.3
- page.execute_script("window.__sampling = false")
+ page.execute_script("window.__sample()")
frames = page.evaluate_script("window.__frames")
widths = frames.map(&:first)
@@ -559,6 +542,38 @@ class ChartSidebarResizeTest < ApplicationSystemTestCase
find("[data-action='app-layout#toggleLeftSidebar']").click
end
+ # Toggles the left sidebar and moves its width transition through its
+ # duration in `steps`, calling window.__sample() after each step is
+ # painted. Left to run on the clock, the 300ms transition could paint only
+ # its first and last frames on a slow machine. The transition is paused as
+ # it starts and finished after the last step, so the charts see its end.
+ def step_left_sidebar(steps: 20)
+ page.execute_script(<<~JS)
+ window.__transition = null;
+ document.addEventListener("transitionrun", function pause(event) {
+ if (event.propertyName !== "width" || event.target.dataset.appLayoutTarget !== "leftSidebar") return;
+ document.removeEventListener("transitionrun", pause);
+ window.__transition = event.target.getAnimations().find((animation) => animation.transitionProperty === "width");
+ window.__transition.pause();
+ });
+ JS
+ toggle_left_sidebar
+ page.evaluate_async_script(<<~JS, steps)
+ const [steps, done] = arguments;
+ // Resize observers run after requestAnimationFrame callbacks and before
+ // the paint, so a task queued from one sees what the frame showed.
+ const afterPaint = (fn) => requestAnimationFrame(() => setTimeout(fn, 0));
+ const step = (i) => {
+ const transition = window.__transition;
+ if (i > steps) { transition.finish(); done(); return; }
+ transition.currentTime = transition.effect.getComputedTiming().duration * i / steps;
+ afterPaint(() => { window.__sample(); step(i + 1); });
+ };
+ const started = () => window.__transition ? step(0) : requestAnimationFrame(started);
+ started();
+ JS
+ end
+
def net_worth_width
page.evaluate_script(%(document.querySelector(#{NET_WORTH.to_json}).clientWidth))
end