Created
November 21, 2013 16:50
-
-
Save kylewelsby/7585329 to your computer and use it in GitHub Desktop.
Test that waits for pub/sub message before asserting.
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
require 'minitest' | |
require 'minitest/autorun' | |
require 'minitest/pride' | |
require 'redis' | |
require 'sidekiq' | |
class ThingWorker | |
include Sidekiq::Worker | |
def perform(message) | |
puts message | |
end | |
end | |
require 'sidekiq/testing' | |
class ThingListener | |
def redis | |
redis ||= Redis.new(:timeout => 10) | |
end | |
def initialize | |
puts "redis is #{redis.connected?} connected?" | |
redis.subscribe('things') do |on| | |
on.subscribe do |channel, s| | |
$subscribed = true | |
puts "Subscribed to #{channel} with #{s} subscription(s)" | |
end | |
on.unsubscribe do |channel, s| | |
puts "Unsubscribed to #{channel} with #{s} subscription(s)" | |
end | |
on.message do |channel, message| | |
$message = true | |
puts "Received message #{message}" | |
ThingWorker.perform_async(message) | |
end | |
end | |
end | |
end | |
class FakeRedisTest < MiniTest::Test | |
def redis | |
redis ||= Redis.new(:timeout => 10) | |
end | |
def setup | |
$message = false | |
$subscribed = false | |
@t1 = Thread.new do | |
ThingListener.new | |
end | |
end | |
def wait_for_subscription | |
return if $subscribed | |
timeout = 10 | |
loop do | |
puts "waiting for subscription #{$subscribed} (timeout in #{timeout})" | |
timeout = timeout - 1 | |
sleep 1 | |
if $subscribed || timeout == 0 | |
break | |
end | |
end | |
end | |
def wait_for_message | |
return if $message | |
timeout = 10 | |
loop do | |
puts "waiting for message #{$message} (timeout in #{timeout})" | |
timeout = timeout - 1 | |
sleep 1 | |
if $message || timeout == 0 | |
break | |
end | |
end | |
end | |
def test_publish | |
wait_for_subscription | |
redis.publish('things', "Hello World") | |
wait_for_message | |
assert_equal 1, ThingWorker.jobs.size | |
end | |
def teardown | |
@t1.exit | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment