We got nominated! Help us out and vote for GitHub as Best Bootstrapped Startup of 2008. (You can vote once a day.) [ hide ]

public
Description: Phusion Passenger (mod_rails)
Homepage: http://www.modrails.com/
Clone URL: git://github.com/FooBarWidget/passenger.git
Click here to lend your support to: passenger and make a donation at www.pledgie.com !
passenger / test / integration_tests.rb
100644 358 lines (313 sloc) 9.875 kb
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
require 'net/http'
require 'uri'
require 'resolv'
require 'socket'
require 'timeout'
require 'support/config'
require 'support/multipart'
require 'support/apache2_config_writer'
require 'passenger/platform_info'
 
include PlatformInfo
 
# TODO: test the 'RailsUserSwitching' and 'RailsDefaultUser' option.
# TODO: test custom page caching directory
 
shared_examples_for "MyCook(tm) beta" do
  it "should be possible to fetch static assets" do
    get('/images/rails.png').should == public_file('images/rails.png')
  end
  
  it "should support page caching on non-index URIs" do
    get('/welcome/cached').should =~ %r{This is the cached version of /welcome/cached}
  end
  
  it "should support page caching on index URIs" do
    get('/uploads').should =~ %r{This is the cached version of /uploads}
  end
  
  it "should not use page caching if the HTTP request is not GET" do
    post('/welcome/cached').should =~ %r{This content should never be displayed}
  end
  
  it "should not be interfered by Rails's default .htaccess dispatcher rules" do
    # Already being tested by all the other tests.
  end
  
  it "should be possible to GET a regular Rails page" do
    get('/').should =~ /Welcome to MyCook/
  end
  
  it "should be possible to pass GET parameters to a Rails page" do
    result = get('/welcome/parameters_test?hello=world&recipe[name]=Green+Bananas')
    result.should =~ %r{<hello>world</hello>}
    result.should =~ %r{<recipe>}
    result.should =~ %r{<name>Green Bananas</name>}
  end
  
  it "should be possible to POST to a Rails page" do
    result = post('/recipes', {
      'recipe[name]' => 'Banana Pancakes',
      'recipe[instructions]' => 'Call 0900-BANANAPANCAKES'
    })
    result.should =~ %r{HTTP method: post}
    result.should =~ %r{Name: Banana Pancakes}
    result.should =~ %r{Instructions: Call 0900-BANANAPANCAKES}
  end
  
  it "should be possible to upload a file" do
    rails_png = File.open("#{@app_root}/public/images/rails.png", 'rb')
    params = {
      'upload[name1]' => 'Kotonoha',
      'upload[name2]' => 'Sekai',
      'upload[data]' => rails_png
    }
    begin
      response = post('/uploads', params)
      rails_png.rewind
      response.should ==
        "name 1 = Kotonoha\n" <<
        "name 2 = Sekai\n" <<
        "data = " << rails_png.read
    ensure
      rails_png.close
    end
  end
  
  it "should properly handle custom headers" do
    response = get_response('/welcome/headers_test')
    response["X-Foo"].should == "Bar"
  end
  
  it "should support restarting via restart.txt" do
    begin
      controller = "#{@app_root}/app/controllers/test_controller.rb"
      restart_file = "#{@app_root}/tmp/restart.txt"
      
      File.open(controller, 'w') do |f|
        f.write %q{
          class TestController < ApplicationController
            layout nil
            def index
              render :text => "foo"
            end
          end
        }
      end
      File.open(restart_file, 'w') do end
      get('/test').should == "foo"
    
      File.open(controller, 'w') do |f|
        f.write %q{
          class TestController < ApplicationController
            layout nil
            def index
              render :text => "bar"
            end
          end
        }
      end
 
      File.open(restart_file, 'w') do end
      get('/test').should == 'bar'
    ensure
      File.unlink(controller) rescue nil
      File.unlink(restart_file) rescue nil
    end
  end
  
  it "should not make the web server crash if the app crashes" do
    post('/welcome/terminate')
    sleep(0.25) # Give the app the time to terminate itself.
    get('/').should =~ /Welcome to MyCook/
  end
  
  if Process.uid == 0
    it "should be running as unprivileged user" do
      post('/welcome/touch')
      begin
        stat = File.stat("#{@app_root}/public/touch.txt")
        stat.uid.should_not == 0
        stat.gid.should_not == 0
      ensure
        File.unlink("#{@app_root}/public/touch.txt") rescue nil
      end
    end
  end
end
 
describe "mod_passenger running in Apache 2" do
  before :all do
    check_hosts_configuration
    Apache2ConfigWriter.new.write
    start_apache
  end
  
  after :all do
    stop_apache
  end
  
  describe ": MyCook(tm) beta running on root URI" do
    before :each do
      @server = "http://mycook.passenger.test:64506"
      @app_root = "stub/mycook"
    end
    
    it_should_behave_like "MyCook(tm) beta"
  end
  
  describe ": MyCook(tm) beta running in a sub-URI" do
    before :each do
      @server = "http://zsfa.passenger.test:64506/mycook"
      @app_root = "stub/mycook"
      File.unlink("stub/zsfa/mycook") rescue nil
      File.symlink("../mycook/public", "stub/zsfa/mycook")
    end
    
    after :each do
      File.unlink("stub/zsfa/mycook") rescue nil
    end
    
    it_should_behave_like "MyCook(tm) beta"
  end
  
  describe ": railsapp running in a sub-URI" do
    before :each do
      @server = "http://zsfa.passenger.test:64506/foo"
      @app_root = "stub/railsapp"
      File.unlink("stub/zsfa/foo") rescue nil
      File.symlink("../railsapp/public", "stub/zsfa/foo")
    end
    
    after :each do
      File.unlink("stub/zsfa/foo") rescue nil
    end
    
    it "should respond to /foo/new" do
      get('/foo/new').should == 'hello world'
    end
    
    it "should not interfere with the ZSFA website" do
      @server = "http://zsfa.passenger.test:64506"
      get('/').should =~ /Zed, you rock\!/
    end
  end
  
  describe "configuration options" do
    it "should ignore the Rails application if RailsAutoDetect is off" do
      @server = "http://norails.passenger.test:64506"
      get('/').should_not =~ /MyCook/
    end
    
    it "setting RailsAutoDetect for one virtual host should not interfere with others" do
      # Already covered by other tests.
    end
  end
  
  describe "error handling" do
    before :each do
      File.unlink("stub/zsfa/app-with-nonexistant-rails-version") rescue nil
      File.unlink("stub/zsfa/app-that-crashes-during-startup") rescue nil
      File.unlink("stub/zsfa/app-with-crashing-vendor-rails") rescue nil
      File.symlink("../broken-railsapp4/public", "stub/zsfa/app-with-nonexistant-rails-version")
      File.symlink("../broken-railsapp/public", "stub/zsfa/app-that-crashes-during-startup")
      File.symlink("../broken-railsapp5/public", "stub/zsfa/app-with-crashing-vendor-rails")
      @server = "http://zsfa.passenger.test:64506"
      @error_page_signature = /<meta name="generator" content="Phusion Passenger">/
    end
    
    after :each do
      File.unlink("stub/zsfa/app-with-nonexistant-rails-version") rescue nil
      File.unlink("stub/zsfa/app-that-crashes-during-startup") rescue nil
      File.unlink("stub/zsfa/app-with-crashing-vendor-rails") rescue nil
    end
    
    it "should display an error page if the Rails application requires a nonexistant Rails version" do
      get("/app-with-nonexistant-rails-version/").should =~ @error_page_signature
    end
    
    it "should display an error page if the Rails application crashes during startup" do
      get("/app-that-crashes-during-startup/").should =~ @error_page_signature
    end
    
    it "should display an error page if the Rails application's vendor'ed Rails crashes" do
      get("/app-with-crashing-vendor-rails/").should =~ @error_page_signature
    end
  end
  
  ##### Helper methods #####
  
  def get(uri)
    return Net::HTTP.get(URI.parse("#{@server}#{uri}"))
  end
  
  def get_response(uri)
    return Net::HTTP.get_response(URI.parse("#{@server}#{uri}"))
  end
  
  def post(uri, params = {})
    url = URI.parse("#{@server}#{uri}")
    if params.values.any? { |x| x.respond_to?(:read) }
      mp = Multipart::MultipartPost.new
      query, headers = mp.prepare_query(params)
      Net::HTTP.start(url.host, url.port) do |http|
        return http.post(url.path, query, headers).body
      end
    else
      return Net::HTTP.post_form(url, params).body
    end
  end
  
  def public_file(name)
    return File.read("#{@app_root}/public/#{name}")
  end
  
  def check_hosts_configuration
    begin
      ok = Resolv.getaddress("passenger.test") == "127.0.0.1"
    rescue Resolv::ResolvError
      ok = false
    end
    if !ok
      message = "To run the integration test, you must update " <<
        "your hosts file.\n" <<
        "Please add these to your /etc/hosts:\n\n" <<
        " 127.0.0.1 passenger.test\n" <<
        " 127.0.0.1 mycook.passenger.test\n" <<
        " 127.0.0.1 zsfa.passenger.test\n" <<
        " 127.0.0.1 norails.passenger.test\n"
      if RUBY_PLATFORM =~ /darwin/
        message << "\n\nThen run:\n\n" <<
          " lookupd -flushcache (OS X Tiger)\n\n" <<
          "-OR-\n\n" <<
          " dscacheutil -flushcache (OS X Leopard)"
      end
      STDERR.puts "---------------------------"
      STDERR.puts message
      exit!
    end
  end
  
  def start_apache
    if File.exist?("stub/apache2/httpd.pid")
      stop_apache
    end
    config_file = File.expand_path("stub/apache2/httpd.conf")
    if !system(HTTPD, "-f", config_file, "-k", "start")
      raise "Could not start a test Apache server"
    end
    begin
      # Wait until the PID file has been created.
      Timeout::timeout(15) do
        while !File.exist?("stub/apache2/httpd.pid")
          sleep(0.25)
        end
      end
      # Wait until Apache is listening on the server port.
      Timeout::timeout(5) do
        done = false
        while !done
          begin
            socket = TCPSocket.new('localhost', 64506)
            socket.close
            done = true
          rescue Errno::ECONNREFUSED
            sleep(0.25)
          end
        end
      end
    rescue Timeout::Error
      raise "Unable to start Apache."
    end
    File.chmod(0666, *Dir['stub/apache2/*.{log,lock,pid}']) rescue nil
    File.chmod(0777, *Dir['stub/mycook/{public,log}']) rescue nil
  end
  
  def stop_apache
    File.chmod(0666, *Dir['stub/apache2/*.{log,lock,pid}']) rescue nil
    begin
      pid = File.read('stub/apache2/httpd.pid').strip.to_i
      Process.kill('SIGTERM', pid)
    rescue
    end
    begin
      # Wait until the PID file is removed.
      Timeout::timeout(15) do
        while File.exist?("stub/apache2/httpd.pid")
          sleep(0.25)
        end
      end
      # Wait until the server socket is closed.
      Timeout::timeout(5) do
        done = false
        while !done
          begin
            socket = TCPSocket.new('localhost', 64506)
            socket.close
            sleep(0.25)
          rescue SystemCallError
            done = true
          end
        end
      end
    rescue Timeout::Error
      raise "Unable to stop Apache."
    end
  end
end