-
Notifications
You must be signed in to change notification settings - Fork 51
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
62 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
# frozen_string_literal: true | ||
|
||
require "cases/helper_cockroachdb" | ||
|
||
module CockroachDB | ||
class TransactionsTest < ActiveRecord::TestCase | ||
class Customer < ActiveRecord::Base | ||
validate :validate_unique_username | ||
|
||
def validate_unique_username | ||
duplicate = Customer.where(username: username).any? | ||
errors.add("Duplicate username!") if duplicate | ||
end | ||
|
||
def to_s | ||
"#{id}:#{name}:#{username}" | ||
end | ||
end | ||
|
||
def setup | ||
conn = ActiveRecord::Base.lease_connection | ||
conn.create_table :customers, force: true do |t| | ||
t.string :name | ||
t.string :username | ||
end | ||
end | ||
|
||
def teardown | ||
conn = ActiveRecord::Base.lease_connection | ||
conn.drop_table :customers, if_exists: true | ||
end | ||
|
||
def test_concurrent_customer_insert_with_processes | ||
concurrency_level = 3 | ||
time_to_start = 2.seconds.from_now | ||
pids = [] | ||
|
||
concurrency_level.times do |i| | ||
pids << Process.fork do | ||
sleep_time = (time_to_start - Time.current).to_f | ||
sleep(sleep_time) if sleep_time > 0 | ||
|
||
begin | ||
c = Customer.new | ||
c.name = "Customer #{i + 1}" | ||
c.username = SecureRandom.uuid | ||
c.save! | ||
puts "Inserted customer with id #{c.id} successfully!" | ||
rescue => e | ||
puts "Process #{Process.pid} - Error: #{e.message}" | ||
end | ||
end | ||
end | ||
|
||
pids.each { |pid| Process.wait(pid) } | ||
|
||
puts "Customers #{Customer.all.map { |c| c.to_s }}" | ||
assert_equal concurrency_level, Customer.count | ||
end | ||
end | ||
end |