繁体   English   中英

将线程同步到WEBrick服务器启动

[英]Synchronize threads to the WEBrick server start

我正在尝试启动一个小型WEBrick服务器以模拟真实的API,以测试我正在开发的Ruby http客户端。 我正在使用基于博客评论的解决方案的修改。

它工作正常,但问题是每次服务器启动时,父线程必须等待任意时间才能加载服务器。 在添加了多个测试之后,它变得非常缓慢。

所以我的问题是: 有没有一种方法可以在服务器线程完成启动WEBRick之后立即同步父线程以继续?

我尝试查看WEBrick参考,搜索了网络,甚至浏览了WEBrick代码,但是如果没有进行一些令人讨厌的猴子补丁,我什么也无法使用。

我对解决该问题的其他方法持开放态度,但我希望使其尽可能不受宝石和图书馆的依赖。 此外,解决方案必须Linux上的Ruby 1.9.2运行

预先感谢您的回答!

require "rack"
class ApiMockServer
  def initialize(port = 4000, pause = 1)
    @block = nil
    @parent_thread = Thread.current
    @thread = Thread.new do
      Rack::Handler::WEBrick.run(self, :Port => port, :Host => "127.0.0.1")
    end

    sleep pause # give the server time to fire up… YUK!
  end

  def stop
    Thread.kill(@thread)
  end

  def attach(&block)
    @block = block
  end

  def detach()
    @block = nil
  end

  def call(env)
    begin
      unless @block
        raise "Specify a handler for the request using attach(block). The " +
          "block should return a valid rack response and can test expectations"
      end
      @block.call(env)
    rescue Exception => e
      @parent_thread.raise e
      [ 500, { 'Content-Type' => 'text/plain', 'Content-Length' => '13' }, [ 'Bad test code' ]]
    end
  end
end

如果您要进行机架测试,为什么不使用Rack :: Test呢?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM