Permalink
Browse files

Make mock owserver support multiple connections

  • Loading branch information...
pedrocr committed Jul 5, 2011
1 parent 9dfe319 commit 53a46c6ab01d2a19d4b2b9e88fbc8f9fb6884724
Showing with 50 additions and 25 deletions.
  1. +45 −20 test/mock_owserver.rb
  2. +5 −5 test/test_helper.rb
View
@@ -1,4 +1,5 @@
require 'socket'
+require 'thread'
module MockOWServer
ERROR = 0
@@ -61,36 +62,60 @@ def write(socket)
class Server
attr_accessor :paths
- attr_reader :write_value
+
+ def write_value
+ @mutex.synchronize do
+ @write_value
+ end
+ end
def initialize(opts={})
@address = opts[:address] || 'localhost'
@port = opts[:port] || 4304
- @stop = false
@paths = opts[:paths] || {}
+ @mutex = Mutex.new
+ end
- @socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
- @socket.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)
- @socket.bind(Socket.pack_sockaddr_in(@port, @address))
- @socket.listen 1
+ def run!
+ @stopped = false
+ @thread = Thread.new do
+ socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
+ socket.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)
+ socket.bind(Socket.pack_sockaddr_in(@port, @address))
+ socket.listen 10
+ while !@stopped
+ begin
+ client, client_sockaddr = socket.accept_nonblock
+ respond(client)
+ rescue Errno::EAGAIN
+ sleep 0.1
+ end
+ end
+ socket.close
+ end
end
- def run
- client, client_sockaddr = @socket.accept
- req = Request.new(client)
- case req.function
- when READ
- Response.new(:data => @paths[req.path]).write(client)
- when DIR
- (@paths[req.path]||[]).each do |dir|
- Response.new(:data => dir).write(client)
+ def respond(client)
+ @mutex.synchronize do
+ req = Request.new(client)
+ case req.function
+ when READ
+ Response.new(:data => @paths[req.path]).write(client)
+ when DIR
+ (@paths[req.path]||[]).each do |dir|
+ Response.new(:data => dir).write(client)
+ end
+ Response.new.write(client)
+ when WRITE
+ @write_value = req.data
+ Response.new.write(client)
end
- Response.new.write(client)
- when WRITE
- @write_value = req.data
- Response.new.write(client)
end
- @socket.close
+ end
+
+ def stop!
+ @stopped = true
+ @thread.join
end
end
end
View
@@ -18,12 +18,12 @@ def with_fake_owserver
Process.waitpid(pid)
end
def with_mock_owserver(paths=nil)
- server = nil
server = MockOWServer::Server.new(:paths => paths)
- t = Thread.new do
- server.run
+ server.run!
+ begin
+ yield server
+ ensure
+ server.stop!
end
- yield server
- t.join
end
end

0 comments on commit 53a46c6

Please sign in to comment.