File: server_spec.rb

package info (click to toggle)
ruby-capybara 3.36.0%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 2,380 kB
  • sloc: ruby: 23,399; javascript: 748; makefile: 11
file content (303 lines) | stat: -rw-r--r-- 9,754 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Capybara::Server do
  it 'should spool up a rack server' do
    app = proc { |_env| [200, {}, ['Hello Server!']] }
    server = described_class.new(app).boot

    res = Net::HTTP.start(server.host, server.port) { |http| http.get('/') }

    expect(res.body).to include('Hello Server')
  end

  it 'should do nothing when no server given' do
    expect do
      described_class.new(nil).boot
    end.not_to raise_error
  end

  it 'should bind to the specified host' do
    # TODO: travis with jruby in container mode has an issue with this test
    skip 'This platform has an issue with this test' if (ENV['TRAVIS'] && (RUBY_ENGINE == 'jruby')) || Gem.win_platform?

    begin
      app = proc { |_env| [200, {}, ['Hello Server!']] }

      Capybara.server_host = '127.0.0.1'
      server = described_class.new(app).boot
      res = Net::HTTP.get(URI("http://127.0.0.1:#{server.port}"))
      expect(res).to eq('Hello Server!')

      Capybara.server_host = '0.0.0.0'
      server = described_class.new(app).boot
      res = Net::HTTP.get(URI("http://127.0.0.1:#{server.port}"))
      expect(res).to eq('Hello Server!')
    ensure
      Capybara.server_host = nil
    end
  end

  it 'should use specified port' do
    Capybara.server_port = 22789

    app = proc { |_env| [200, {}, ['Hello Server!']] }
    server = described_class.new(app).boot

    res = Net::HTTP.start(server.host, 22789) { |http| http.get('/') }
    expect(res.body).to include('Hello Server')

    Capybara.server_port = nil
  end

  it 'should use given port' do
    app = proc { |_env| [200, {}, ['Hello Server!']] }
    server = described_class.new(app, port: 22790).boot

    res = Net::HTTP.start(server.host, 22790) { |http| http.get('/') }
    expect(res.body).to include('Hello Server')

    Capybara.server_port = nil
  end

  it 'should find an available port' do
    responses = ['Hello Server!', 'Hello Second Server!']
    apps = responses.map do |response|
      proc { |_env| [200, {}, [response]] }
    end
    servers = apps.map { |app| described_class.new(app).boot }

    servers.each_with_index do |server, idx|
      result = Net::HTTP.start(server.host, server.port) { |http| http.get('/') }
      expect(result.body).to include(responses[idx])
    end
  end

  it 'should handle that getting available ports fails randomly' do
    # Use a port to force a EADDRINUSE error to be generated
    server = TCPServer.new('0.0.0.0', 0)
    server_port = server.addr[1]
    d_server = instance_double('TCPServer', addr: [nil, server_port, nil, nil], close: nil)
    call_count = 0
    allow(TCPServer).to receive(:new).and_wrap_original do |m, *args|
      call_count.zero? ? d_server : m.call(*args)
    ensure
      call_count += 1
    end

    port = described_class.new(Object.new, host: '0.0.0.0').port
    expect(port).not_to eq(server_port)
  ensure
    server&.close
  end

  it 'should return its #base_url' do
    app = proc { |_env| [200, {}, ['Hello Server!']] }
    server = described_class.new(app).boot
    uri = ::Addressable::URI.parse(server.base_url)
    expect(uri.to_hash).to include(scheme: 'http', host: server.host, port: server.port)
  end

  it 'should call #clamp on the puma configuration to ensure that environment is a string' do
    Capybara.server = :puma
    app_proc = proc { |_env| [200, {}, ['Hello Puma!']] }
    require 'puma'
    allow(Puma::Server).to receive(:new).and_wrap_original do |method, app, events, options|
      # If #clamp is not called on the puma config then this will be a Proc
      expect(options.fetch(:environment)).to be_a(String)
      method.call(app, events, options)
    end
    server = described_class.new(app_proc).boot
    expect(Puma::Server).to have_received(:new).with(
      anything,
      anything,
      satisfy { |opts| opts.final_options[:Port] == server.port }
    )
  ensure
    Capybara.server = :default
  end

  xit 'should support SSL' do
    key = File.join(Dir.pwd, 'spec', 'fixtures', 'key.pem')
    cert = File.join(Dir.pwd, 'spec', 'fixtures', 'certificate.pem')
    Capybara.server = :puma, { Host: "ssl://#{Capybara.server_host}?key=#{key}&cert=#{cert}" }
    app = proc { |_env| [200, {}, ['Hello SSL Server!']] }
    server = described_class.new(app).boot

    expect do
      Net::HTTP.start(server.host, server.port, max_retries: 0) { |http| http.get('/__identify__') }
    end.to(raise_error do |e|
      expect(e.is_a?(EOFError) || e.is_a?(Net::ReadTimeout)).to be true
    end)

    res = Net::HTTP.start(server.host, server.port, use_ssl: true, verify_mode: OpenSSL::SSL::VERIFY_NONE) do |https|
      https.get('/')
    end

    expect(res.body).to include('Hello SSL Server!')
    uri = ::Addressable::URI.parse(server.base_url)
    expect(uri.to_hash).to include(scheme: 'https', host: server.host, port: server.port)
  ensure
    Capybara.server = :default
  end

  context 'When Capybara.reuse_server is true' do
    let!(:old_reuse_server) { Capybara.reuse_server }

    before do
      Capybara.reuse_server = true
    end

    after do
      Capybara.reuse_server = old_reuse_server
    end

    it 'should use the existing server if it already running' do
      app = proc { |_env| [200, {}, ['Hello Server!']] }

      servers = Array.new(2) { described_class.new(app).boot }

      servers.each do |server|
        res = Net::HTTP.start(server.host, server.port) { |http| http.get('/') }
        expect(res.body).to include('Hello Server')
      end

      expect(servers[0].port).to eq(servers[1].port)
    end

    it 'detects and waits for all reused server sessions pending requests' do
      done = 0

      app = proc do |env|
        request = Rack::Request.new(env)
        sleep request.params['wait_time'].to_f
        done += 1
        [200, {}, ['Hello Server!']]
      end

      server1 = described_class.new(app).boot
      server2 = described_class.new(app).boot

      expect do
        start_request(server1, 1.0)
        start_request(server2, 3.0)
        server1.wait_for_pending_requests
      end.to change { done }.from(0).to(2)
      expect(server2.send(:pending_requests?)).to eq(false)
    end
  end

  context 'When Capybara.reuse_server is false' do
    before do
      @old_reuse_server = Capybara.reuse_server
      Capybara.reuse_server = false
    end

    after do
      Capybara.reuse_server = @old_reuse_server # rubocop:disable RSpec/InstanceVariable
    end

    it 'should not reuse an already running server' do
      app = proc { |_env| [200, {}, ['Hello Server!']] }

      servers = Array.new(2) { described_class.new(app).boot }

      servers.each do |server|
        res = Net::HTTP.start(server.host, server.port) { |http| http.get('/') }
        expect(res.body).to include('Hello Server')
      end

      expect(servers[0].port).not_to eq(servers[1].port)
    end

    it 'detects and waits for only one sessions pending requests' do
      done = 0

      app = proc do |env|
        request = Rack::Request.new(env)
        sleep request.params['wait_time'].to_f
        done += 1
        [200, {}, ['Hello Server!']]
      end

      server1 = described_class.new(app).boot
      server2 = described_class.new(app).boot

      expect do
        start_request(server1, 1.0)
        start_request(server2, 3.0)
        server1.wait_for_pending_requests
      end.to change { done }.from(0).to(1)
      expect(server2.send(:pending_requests?)).to eq(true)
      expect do
        server2.wait_for_pending_requests
      end.to change { done }.from(1).to(2)
    end
  end

  it 'should raise server errors when the server errors before the timeout' do
    Capybara.register_server :kaboom do
      sleep 0.1
      raise 'kaboom'
    end
    Capybara.server = :kaboom

    expect do
      described_class.new(proc { |e| }).boot
    end.to raise_error(RuntimeError, 'kaboom')
  ensure
    Capybara.server = :default
  end

  it 'should raise an error when there are pending requests' do
    app = proc do |env|
      request = Rack::Request.new(env)
      sleep request.params['wait_time'].to_f
      [200, {}, ['Hello Server!']]
    end

    server = described_class.new(app).boot

    expect do
      start_request(server, 59.0)
      server.wait_for_pending_requests
    end.not_to raise_error

    expect do
      start_request(server, 61.0)
      server.wait_for_pending_requests
    end.to raise_error('Requests did not finish in 60 seconds: ["/?wait_time=61.0"]')
  end

  it 'is not #responsive? when Net::HTTP raises a SystemCallError' do
    app = -> { [200, {}, ['Hello, world']] }
    server = described_class.new(app)
    allow(Net::HTTP).to receive(:start).and_raise(SystemCallError.allocate)
    expect(server.responsive?).to eq false
  end

  [EOFError, Net::ReadTimeout].each do |err|
    it "should attempt an HTTPS connection if HTTP connection returns #{err}" do
      app = -> { [200, {}, ['Hello, world']] }
      ordered_errors = [Errno::ECONNREFUSED, err]
      allow(Net::HTTP).to receive(:start).with(anything, anything, hash_excluding(:use_ssl)) do
        raise ordered_errors.shift
      end
      response = Net::HTTPSuccess.allocate
      allow(response).to receive(:body).and_return app.object_id.to_s
      allow(Net::HTTP).to receive(:start).with(anything, anything, hash_including(use_ssl: true)).and_return(response).once
      described_class.new(app).boot
      expect(Net::HTTP).to have_received(:start).exactly(3).times
    end
  end

  def start_request(server, wait_time)
    # Start request, but don't wait for it to finish
    socket = TCPSocket.new(server.host, server.port)
    socket.write "GET /?wait_time=#{wait_time} HTTP/1.0\r\n\r\n"
    sleep 0.1
    socket.close
    sleep 0.1
  end
end