Make IDs more time-sortable in tests

In order for model ordering to work as expected in tests, we need to
keep two properties:

- Fixtures are all created in the past
- Models sort in the order that they were created

This allows us to do things like this:

    post cards_path, params: { ... }
    created_card = Card.last

When using UUIDv7 PKs rather than sequential integers, we have to make
sure a couple of things happen in order for this still to be true:

- Fixtures should generate deterministic IDs that translate to UUIDs
  that would have been created in the past (i.e. before today)
- Newly created objects must have enough precision in their timestamps
  so that they sort in the order they were created, and their random
  component doesn't come into play.

To solve this, we use the deterministic numeric ID as a number of
milliseconds after an early year. And we ensure that the new timestamps
we create have sub-millisecond precision.
This commit is contained in:
Kevin McConnell
2025-11-13 16:18:44 +00:00
committed by Mike Dalessio
parent 4f4bf5bee1
commit 59dd8ca549
15 changed files with 34 additions and 29 deletions
@@ -16,7 +16,7 @@ class Boards::ColumnsControllerTest < ActionDispatch::IntegrationTest
assert_response :success assert_response :success
end end
assert_equal "New Column", boards(:writebook).columns.order(created_at: :desc).first.name assert_equal "New Column", boards(:writebook).columns.last.name
end end
test "update" do test "update" do
+1 -1
View File
@@ -20,7 +20,7 @@ class BoardsControllerTest < ActionDispatch::IntegrationTest
post boards_path, params: { board: { name: "Remodel Punch List" } } post boards_path, params: { board: { name: "Remodel Punch List" } }
end end
board = Board.order(created_at: :desc).first board = Board.last
assert_redirected_to board_path(board) assert_redirected_to board_path(board)
assert_includes board.users, users(:kevin) assert_includes board.users, users(:kevin)
assert_equal "Remodel Punch List", board.name assert_equal "Remodel Punch List", board.name
@@ -26,7 +26,7 @@ class Cards::PublishesControllerTest < ActionDispatch::IntegrationTest
end end
end end
new_card = Card.order(created_at: :desc).first new_card = Card.last
assert new_card.drafted? assert new_card.drafted?
assert_redirected_to new_card assert_redirected_to new_card
end end
+1 -1
View File
@@ -20,7 +20,7 @@ class CardsControllerTest < ActionDispatch::IntegrationTest
post board_cards_path(boards(:writebook)) post board_cards_path(boards(:writebook))
end end
card = Card.order(created_at: :desc).first card = Card.last
assert card.drafted? assert card.drafted?
assert_redirected_to card assert_redirected_to card
end end
+1 -1
View File
@@ -16,7 +16,7 @@ class FiltersControllerTest < ActionDispatch::IntegrationTest
end end
assert_response :success assert_response :success
filter = Filter.order(created_at: :desc).first filter = Filter.last
assert_predicate filter.indexed_by, :closed? assert_predicate filter.indexed_by, :closed?
assert_predicate filter.assignment_status, :unassigned? assert_predicate filter.assignment_status, :unassigned?
assert_equal [ tags(:mobile) ], filter.tags assert_equal [ tags(:mobile) ], filter.tags
+1 -1
View File
@@ -35,7 +35,7 @@ class WebhooksControllerTest < ActionDispatch::IntegrationTest
} }
end end
webhook = Webhook.order(created_at: :desc).first webhook = Webhook.last
assert_redirected_to board_webhook_path(webhook.board, webhook) assert_redirected_to board_webhook_path(webhook.board, webhook)
assert_equal board, webhook.board assert_equal board, webhook.board
+2 -2
View File
@@ -18,7 +18,7 @@ class Card::CloseableTest < ActiveSupport::TestCase
end end
assert cards(:logo).closed? assert cards(:logo).closed?
assert cards(:logo).events.order(created_at: :desc).first.action.card_closed? assert cards(:logo).events.last.action.card_closed?
assert_equal users(:kevin), cards(:logo).closed_by assert_equal users(:kevin), cards(:logo).closed_by
end end
@@ -29,6 +29,6 @@ class Card::CloseableTest < ActiveSupport::TestCase
cards(:shipping).reopen cards(:shipping).reopen
end end
assert cards(:shipping).reload.open? assert cards(:shipping).reload.open?
assert cards(:shipping).events.order(created_at: :desc).first.action.card_reopened? assert cards(:shipping).events.last.action.card_reopened?
end end
end end
@@ -45,7 +45,7 @@ class Card::Eventable::SystemCommenterTest < ActiveSupport::TestCase
def assert_system_comment(expected_comment) def assert_system_comment(expected_comment)
assert_difference -> { @card.comments.count }, 1 do assert_difference -> { @card.comments.count }, 1 do
yield yield
comment = @card.comments.order(created_at: :desc).first comment = @card.comments.last
assert comment.creator.system? assert comment.creator.system?
assert_match Regexp.new(expected_comment.strip, Regexp::IGNORECASE), comment.body.to_plain_text.strip assert_match Regexp.new(expected_comment.strip, Regexp::IGNORECASE), comment.body.to_plain_text.strip
end end
+2 -2
View File
@@ -26,7 +26,7 @@ class Card::PostponableTest < ActiveSupport::TestCase
end end
assert_equal users(:david), card.not_now.user assert_equal users(:david), card.not_now.user
assert card.events.order(created_at: :desc).first.action.card_postponed? assert card.events.last.action.card_postponed?
assert_changes -> { card.reload.postponed? }, to: false do assert_changes -> { card.reload.postponed? }, to: false do
card.resume card.resume
@@ -42,7 +42,7 @@ class Card::PostponableTest < ActiveSupport::TestCase
end end
end end
assert card.events.order(created_at: :desc).first.action.card_auto_postponed? assert card.events.last.action.card_auto_postponed?
end end
test "scopes" do test "scopes" do
+2 -2
View File
@@ -34,7 +34,7 @@ class Card::StatusesTest < ActiveSupport::TestCase
@card = boards(:writebook).cards.create! creator: users(:kevin), title: "Published Card", status: :published @card = boards(:writebook).cards.create! creator: users(:kevin), title: "Published Card", status: :published
end end
event = Event.order(created_at: :desc).first event = Event.last
assert_equal @card, event.eventable assert_equal @card, event.eventable
assert_equal "card_published", event.action assert_equal "card_published", event.action
end end
@@ -47,7 +47,7 @@ class Card::StatusesTest < ActiveSupport::TestCase
card.publish card.publish
end end
event = Event.order(created_at: :desc).first event = Event.last
assert_equal card, event.eventable assert_equal card, event.eventable
assert_equal "card_published", event.action assert_equal "card_published", event.action
end end
+1 -1
View File
@@ -10,7 +10,7 @@ class Card::TaggableTest < ActiveSupport::TestCase
@card.toggle_tag_with "ruby" @card.toggle_tag_with "ruby"
end end
assert_equal "ruby", @card.tags.order(created_at: :desc).first.title assert_equal "ruby", @card.tags.last.title
assert_difference -> { @card.tags.count }, -1 do assert_difference -> { @card.tags.count }, -1 do
@card.toggle_tag_with "ruby" @card.toggle_tag_with "ruby"
+3 -3
View File
@@ -23,7 +23,7 @@ class CardTest < ActiveSupport::TestCase
cards(:logo).comments.create!(body: "Agreed.") cards(:logo).comments.create!(body: "Agreed.")
end end
assert_equal "Agreed.", cards(:logo).comments.order(created_at: :desc).first.body.to_plain_text.chomp assert_equal "Agreed.", cards(:logo).comments.last.body.to_plain_text.chomp
end end
test "assignment states" do test "assignment states" do
@@ -38,7 +38,7 @@ class CardTest < ActiveSupport::TestCase
cards(:logo).toggle_assignment users(:kevin) cards(:logo).toggle_assignment users(:kevin)
end end
assert_not cards(:logo).assigned_to?(users(:kevin)) assert_not cards(:logo).assigned_to?(users(:kevin))
unassign_event = Event.order(created_at: :desc).first unassign_event = Event.last
assert_equal "card_unassigned", unassign_event.action assert_equal "card_unassigned", unassign_event.action
assert_equal [ users(:kevin) ], unassign_event.assignees assert_equal [ users(:kevin) ], unassign_event.assignees
@@ -46,7 +46,7 @@ class CardTest < ActiveSupport::TestCase
cards(:logo).toggle_assignment users(:kevin) cards(:logo).toggle_assignment users(:kevin)
end end
assert cards(:logo).assigned_to?(users(:kevin)) assert cards(:logo).assigned_to?(users(:kevin))
assign_event = Event.order(created_at: :desc).first assign_event = Event.last
assert_equal "card_assigned", assign_event.action assert_equal "card_assigned", assign_event.action
assert_equal [ users(:kevin) ], assign_event.assignees assert_equal [ users(:kevin) ], assign_event.assignees
end end
+1 -1
View File
@@ -39,7 +39,7 @@ class Notifier::EventNotifierTest < ActiveSupport::TestCase
Notifier.for(events(:logo_published)).notify Notifier.for(events(:logo_published)).notify
assert_equal cards(:logo), Notification.order(created_at: :desc).first.source.eventable assert_equal cards(:logo), Notification.last.source.eventable
end end
test "assignment events only create a notification for the assignee" do test "assignment events only create a notification for the assignee" do
-1
View File
@@ -40,7 +40,6 @@ class SmokeTest < ApplicationSystemTestCase
notif = notifications(:logo_comment_david_mention_by_jz) notif = notifications(:logo_comment_david_mention_by_jz)
skip("Grouped notifications and the new UUID ids are making this test flaky")
assert_selector "div##{dom_id(notif)}" assert_selector "div##{dom_id(notif)}"
within_window(open_new_window) { visit card_url(notif.card) } within_window(open_new_window) { visit card_url(notif.card) }
+16 -10
View File
@@ -94,19 +94,20 @@ module FixturesTestHelper
# so that UUIDs sort in the same order as integer IDs # so that UUIDs sort in the same order as integer IDs
fixture_int = Zlib.crc32("fixtures/#{label}") % (2**30 - 1) fixture_int = Zlib.crc32("fixtures/#{label}") % (2**30 - 1)
# Use fixture_int as second offset from a fixed base time (1 year before 2025-01-01) # Translate the deterministic order into times in the past, so that records
# This ensures all fixtures are in the past, and new test records are newest # created during test runs are also always newer than the fixtures.
base_time = Time.utc(2024, 1, 1, 0, 0, 0) base_time = Time.utc(2024, 1, 1, 0, 0, 0)
timestamp = base_time + fixture_int.seconds timestamp = base_time + (fixture_int / 1000.0)
uuid_v7_with_timestamp(timestamp, label) uuid_v7_with_timestamp(timestamp, label)
end end
def uuid_v7_with_timestamp(time, seed_string) def uuid_v7_with_timestamp(time, seed_string)
# Generate UUIDv7 with custom timestamp and deterministic random bits # Generate UUIDv7 with custom timestamp and deterministic random bits
# Format: 48-bit timestamp_ms | 12-bit random | 4-bit version | 62-bit random # Format: 48-bit timestamp_ms | 12-bit sub_ms_precision | 4-bit version | 62-bit random
timestamp_ms = (time.to_f * 1000).to_i time_ms = time.to_f * 1000
timestamp_ms = time_ms.to_i
# 48-bit timestamp (milliseconds since epoch) # 48-bit timestamp (milliseconds since epoch)
bytes = [] bytes = []
@@ -117,13 +118,18 @@ module FixturesTestHelper
bytes[4] = (timestamp_ms >> 8) & 0xff bytes[4] = (timestamp_ms >> 8) & 0xff
bytes[5] = timestamp_ms & 0xff bytes[5] = timestamp_ms & 0xff
# Derive deterministic "random" bits from seed_string # Use the 12-bit rand_a field for sub-millisecond precision
# Extract fractional milliseconds and convert to 12-bit value (0-4095)
# This gives us ~0.244 microsecond precision
frac_ms = time_ms - timestamp_ms
sub_ms_precision = (frac_ms * 4096).to_i & 0xfff
# Derive deterministic "random" bits from seed_string for the remaining random bits
hash = Digest::MD5.hexdigest(seed_string) hash = Digest::MD5.hexdigest(seed_string)
# 12-bit random + 4-bit version (0111 for v7) # 12-bit sub-ms precision + 4-bit version (0111 for v7)
rand_a = hash[0...3].to_i(16) & 0xfff bytes[6] = ((sub_ms_precision >> 8) & 0x0f) | 0x70 # version 7
bytes[6] = ((rand_a >> 8) & 0x0f) | 0x70 # version 7 bytes[7] = sub_ms_precision & 0xff
bytes[7] = rand_a & 0xff
# 2-bit variant (10) + 62-bit random # 2-bit variant (10) + 62-bit random
rand_b = hash[3...19].to_i(16) & ((2**62) - 1) rand_b = hash[3...19].to_i(16) & ((2**62) - 1)