Class: StubServer

Inherits:
Object
  • Object
show all
Defined in:
lib/stub_server.rb,
lib/stub_server/version.rb

Constant Summary collapse

VERSION =
"0.1.0"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(port, replies, ssl: false, json: false, webrick: {}) ⇒ StubServer

Returns a new instance of StubServer.



14
15
16
17
18
19
20
# File 'lib/stub_server.rb', line 14

def initialize(port, replies, ssl: false, json: false, webrick: {})
  @port = port
  @replies = replies
  @ssl = ssl
  @json = json
  @webrick = webrick
end

Class Method Details

.open(port, replies, **options) ⇒ Object



6
7
8
9
10
11
12
# File 'lib/stub_server.rb', line 6

def self.open(port, replies, **options)
  server = new(port, replies, **options)
  server.boot
  yield server
ensure
  server.shutdown
end

Instance Method Details

#bootObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/stub_server.rb', line 22

def boot
  Thread.new do
    options = {
      Port: @port,
      Logger: WEBrick::Log.new("/dev/null"),
      AccessLog: []
    }

    if @ssl
      require 'webrick/https'
      require 'openssl' # can be slow / break ... so keeping it nested

      options.merge!(
        SSLEnable: true,
        SSLVerifyClient: OpenSSL::SSL::VERIFY_NONE,
        SSLCertificate: OpenSSL::X509::Certificate.new(@ssl.fetch(:cert)),
        SSLPrivateKey: OpenSSL::PKey::RSA.new(@ssl.fetch(:key)),
        SSLCertName: [["CN", 'not-a-valid-cert']]
      )
    end

    options.merge!(@webrick)

    Rack::Handler::WEBrick.run(self, options) { |s| @server = s }
  end
end

#call(env) ⇒ Object



64
65
66
67
68
69
70
71
72
73
# File 'lib/stub_server.rb', line 64

def call(env)
  path = env.fetch("PATH_INFO")
  code, headers, body = @replies[path]
  unless code
    warn "StubServer: Missing reply for path #{path}" # some clients does not show current url when failing
    raise
  end
  body = [body.to_json] if @json
  [code, headers, body]
end

#shutdownObject



75
76
77
# File 'lib/stub_server.rb', line 75

def shutdown
  @server.shutdown if @server
end

#waitObject



49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/stub_server.rb', line 49

def wait
  Timeout.timeout(10) do
    loop do
      begin
        socket = TCPSocket.new('localhost', @port)
        socket.close if socket
        sleep 0.1 if ENV['CI']
        return
      rescue Errno::ECONNREFUSED
        nil
      end
    end
  end
end