Skip to content

Instantly share code, notes, and snippets.

@tank-bohr
Created February 23, 2016 13:03
Show Gist options
  • Save tank-bohr/04bfa7ad1b6104c586be to your computer and use it in GitHub Desktop.
Save tank-bohr/04bfa7ad1b6104c586be to your computer and use it in GitHub Desktop.
class Synchronizer
module ClassMethods
attr_reader :m, :cv
def init!
@m = Mutex.new
@cv = ConditionVariable.new
end
def wait
m.synchronize { cv.wait(m) }
end
def pass
m.synchronize { cv.signal }
end
end
extend ClassMethods
init!
end
require 'test_helper'
require 'eventmachine'
require 'synchronizer'
require 'socket'
class SichuanTest < Minitest::Test
module TestServer
def post_init
Thread.current[:post_init_received] = true
Synchronizer.pass
end
def receive_data(data)
Thread.current[:received_data] = data.chomp
Synchronizer.pass
end
def unbind
Thread.current[:unbind_received] = true
Synchronizer.pass
end
end
def test_start_server
thread = Thread.new {
EventMachine.run {
EventMachine.start_server '127.0.0.1', 2222, TestServer
Synchronizer.pass
}
}
Synchronizer.wait
socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM)
sockaddr = Socket.pack_sockaddr_in(2222, '127.0.0.1')
assert_equal 0, socket.connect(sockaddr)
Synchronizer.wait
assert_equal true, thread[:post_init_received]
socket.puts 'test-test'
Synchronizer.wait
assert_equal 'test-test', thread[:received_data]
socket.close
Synchronizer.wait
assert_equal true, thread[:unbind_received]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment