简体   繁体   English

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

[英]Synchronize threads to the WEBrick server start

I am trying to start a small WEBrick server to mock a real API, to test a Ruby http client I am developing. 我正在尝试启动一个小型WEBrick服务器以模拟真实的API,以测试我正在开发的Ruby http客户端。 I am using a modified solution of the one based in this blog comment. 我正在使用基于博客评论的解决方案的修改。

It works fine, but the problem is that each time the server starts, the parent thread has to wait an arbitrary amount of time for the server to load. 它工作正常,但问题是每次服务器启动时,父线程必须等待任意时间才能加载服务器。 And after adding several tests it gets really slow. 在添加了多个测试之后,它变得非常缓慢。

So my question is: is there a way to synchronize the parent thread to continue right after the server thread has finished starting WEBRick? 所以我的问题是: 有没有一种方法可以在服务器线程完成启动WEBRick之后立即同步父线程以继续?

I tried looking at the WEBrick reference, searched the web and even had a look in the WEBrick code, but I got nothing I could use without some really nasty monkey patching. 我尝试查看WEBrick参考,搜索了网络,甚至浏览了WEBrick代码,但是如果没有进行一些令人讨厌的猴子补丁,我什么也无法使用。

I'm open to other approaches to the problem, but I would like to keep it as dependency-free to gems and libraries as possible. 我对解决该问题的其他方法持开放态度,但我希望使其尽可能不受宝石和图书馆的依赖。 Also, the solutions must run in Ruby 1.9.2 , on Linux . 此外,解决方案必须Linux上的Ruby 1.9.2运行

Thanks in advance for the answers! 预先感谢您的回答!

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