public
Description: GitHub Blog Badges for Everyone
Homepage: http://drnicjavascript.rubyforge.org/github_badge/
Clone URL: git://github.com/drnic/github-badges.git
github-badges / lib / jstest.rb
100644 389 lines (327 sloc) 9.111 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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
require 'rake/tasklib'
require 'thread'
require 'webrick'
require 'fileutils'
include FileUtils
 
class Browser
  def supported?; true; end
  def setup ; end
  def open(url) ; end
  def teardown ; end
 
  def host
    require 'rbconfig'
    Config::CONFIG['host']
  end
  
  def macos?
    host.include?('darwin')
  end
  
  def windows?
    host.include?('mswin')
  end
  
  def linux?
    host.include?('linux')
  end
  
  def applescript(script)
    raise "Can't run AppleScript on #{host}" unless macos?
    system "osascript -e '#{script}' 2>&1 >/dev/null"
  end
end
 
class FirefoxBrowser < Browser
  def initialize(path=File.join(ENV['ProgramFiles'] || 'c:\Program Files', '\Mozilla Firefox\firefox.exe'))
    @path = path
  end
 
  def visit(url)
    system("open -a Firefox '#{url}'") if macos?
    system("#{@path} #{url}") if windows?
    system("firefox #{url}") if linux?
  end
 
  def to_s
    "Firefox"
  end
end
 
class SafariBrowser < Browser
  def supported?
    macos?
  end
  
  def setup
    applescript('tell application "Safari" to make new document')
  end
  
  def visit(url)
    applescript('tell application "Safari" to set URL of front document to "' + url + '"')
  end
 
  def teardown
    #applescript('tell application "Safari" to close front document')
  end
 
  def to_s
    "Safari"
  end
end
 
class IEBrowser < Browser
  def setup
    require 'win32ole' if windows?
  end
 
  def supported?
    windows?
  end
  
  def visit(url)
    if windows?
      ie = WIN32OLE.new('InternetExplorer.Application')
      ie.visible = true
      ie.Navigate(url)
      while ie.ReadyState != 4 do
        sleep(1)
      end
    end
  end
 
  def to_s
    "Internet Explorer"
  end
end
 
class KonquerorBrowser < Browser
  @@configDir = File.join((ENV['HOME'] || ''), '.kde', 'share', 'config')
  @@globalConfig = File.join(@@configDir, 'kdeglobals')
  @@konquerorConfig = File.join(@@configDir, 'konquerorrc')
 
  def supported?
    linux? && File.exist?(@@configDir)
  end
 
  # Forces KDE's default browser to be Konqueror during the tests, and forces
  # Konqueror to open external URL requests in new tabs instead of a new
  # window.
  def setup
    cd @@configDir, :verbose => false do
      copy @@globalConfig, "#{@@globalConfig}.bak", :preserve => true, :verbose => false
      copy @@konquerorConfig, "#{@@konquerorConfig}.bak", :preserve => true, :verbose => false
      # Too lazy to write it in Ruby... Is sed dependency so bad?
      system "sed -ri /^BrowserApplication=/d '#{@@globalConfig}'"
      system "sed -ri /^KonquerorTabforExternalURL=/s:false:true: '#{@@konquerorConfig}'"
    end
  end
 
  def teardown
    cd @@configDir, :verbose => false do
      copy "#{@@globalConfig}.bak", @@globalConfig, :preserve => true, :verbose => false
      copy "#{@@konquerorConfig}.bak", @@konquerorConfig, :preserve => true, :verbose => false
    end
  end
  
  def visit(url)
    system("kfmclient openURL #{url}")
  end
  
  def to_s
    "Konqueror"
  end
end
 
class OperaBrowser < Browser
  def initialize(path='c:\Program Files\Opera\Opera.exe')
    @path = path
  end
 
  def supported?
    if linux?
      return system("which opera")
    end
  end
  
  def setup
    if windows?
      puts %{
MAJOR ANNOYANCE on Windows.
You have to shut down Opera manually after each test
for the script to proceed.
Any suggestions on fixing this is GREATLY appreciated!
Thank you for your understanding.
}
    end
  end
  
  def visit(url)
    applescript('tell application "Opera" to GetURL "' + url + '"') if macos?
    system("#{@path} #{url}") if windows?
    system("opera #{url}") if linux?
  end
 
  def to_s
    "Opera"
  end
end
 
# shut up, webrick :-)
class ::WEBrick::HTTPServer
  def access_log(config, req, res)
    # nop
  end
end
 
class ::WEBrick::BasicLog
  def log(level, data)
    # nop
  end
end
 
class WEBrick::HTTPResponse
  alias send send_response
  def send_response(socket)
    send(socket) unless fail_silently?
  end
  
  def fail_silently?
    @fail_silently
  end
  
  def fail_silently
    @fail_silently = true
  end
end
 
class WEBrick::HTTPRequest
  def to_json
    headers = []
    each { |k, v| headers.push "#{k.inspect}: #{v.inspect}" }
    headers = "{" << headers.join(', ') << "}"
    %({ "headers": #{headers}, "body": #{body.inspect}, "method": #{request_method.inspect} })
  end
end
 
class WEBrick::HTTPServlet::AbstractServlet
  def prevent_caching(res)
    res['ETag'] = nil
    res['Last-Modified'] = Time.now + 100**4
    res['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'
    res['Pragma'] = 'no-cache'
    res['Expires'] = Time.now - 100**4
  end
end
 
class BasicServlet < WEBrick::HTTPServlet::AbstractServlet
  def do_GET(req, res)
    prevent_caching(res)
    res['Content-Type'] = "text/plain"
    
    req.query.each do |k, v|
      res[k] = v unless k == 'responseBody'
    end
    res.body = req.query["responseBody"]
    
    raise WEBrick::HTTPStatus::OK
  end
  
  def do_POST(req, res)
    do_GET(req, res)
  end
end
 
class SlowServlet < BasicServlet
  def do_GET(req, res)
    sleep(2)
    super
  end
end
 
class DownServlet < BasicServlet
  def do_GET(req, res)
    res.fail_silently
  end
end
 
class InspectionServlet < BasicServlet
  def do_GET(req, res)
    prevent_caching(res)
    res['Content-Type'] = "application/json"
    res.body = req.to_json
    raise WEBrick::HTTPStatus::OK
  end
end
 
class NonCachingFileHandler < WEBrick::HTTPServlet::FileHandler
  def do_GET(req, res)
    super
    set_default_content_type(res, req.path)
    prevent_caching(res)
  end
  
  def set_default_content_type(res, path)
    res['Content-Type'] = case path
      when /\.js$/ then 'text/javascript'
      when /\.html$/ then 'text/html'
      when /\.css$/ then 'text/css'
      else 'text/plain'
    end
  end
end
 
class JavaScriptTestTask < ::Rake::TaskLib
 
  def initialize(name=:test, port=4711)
    @name = name
    @tests = []
    @browsers = []
    @port = port
    @queue = Queue.new
 
    @server = WEBrick::HTTPServer.new(:Port => @port) # TODO: make port configurable
    @server.mount_proc("/results") do |req, res|
      @queue.push({
        :tests => req.query['tests'].to_i,
        :assertions => req.query['assertions'].to_i,
        :failures => req.query['failures'].to_i,
        :errors => req.query['errors'].to_i
      })
      res.body = "OK"
    end
    @server.mount("/response", BasicServlet)
    @server.mount("/slow", SlowServlet)
    @server.mount("/down", DownServlet)
    @server.mount("/inspect", InspectionServlet)
    yield self if block_given?
    define
  end
 
  def define
    task @name do
      trap("INT") { @server.shutdown }
      t = Thread.new { @server.start }
      
      # run all combinations of browsers and tests
      @browsers.each do |browser|
        if browser.supported?
          t0 = Time.now
          results = {:tests => 0, :assertions => 0, :failures => 0, :errors => 0}
          errors = []
          failures = []
          browser.setup
          puts "\nStarted tests in #{browser}"
          @tests.each do |test|
            params = "resultsURL=http://localhost:#{@port}/results&t=" + ("%.6f" % Time.now.to_f)
            if test.is_a?(Hash)
              params << "&tests=#{test[:testcases]}" if test[:testcases]
              test = test[:url]
            end
            browser.visit("http://localhost:#{@port}#{test}?#{params}")
 
            result = @queue.pop
            result.each { |k, v| results[k] += v }
            value = "."
            
            if result[:failures] > 0
              value = "F"
              failures.push(test)
            end
            
            if result[:errors] > 0
              value = "E"
              errors.push(test)
            end
            
            print value
          end
          
          puts "\nFinished in #{(Time.now - t0).round.to_s} seconds."
          puts " Failures: #{failures.join(', ')}" unless failures.empty?
          puts " Errors: #{errors.join(', ')}" unless errors.empty?
          puts "#{results[:tests]} tests, #{results[:assertions]} assertions, #{results[:failures]} failures, #{results[:errors]} errors"
          browser.teardown
        else
          puts "\nSkipping #{browser}, not supported on this OS"
        end
      end
 
      @server.shutdown
      t.join
    end
  end
 
  def mount(path, dir=nil)
    dir = Dir.pwd + path unless dir
 
    # don't cache anything in our tests
    @server.mount(path, NonCachingFileHandler, dir)
  end
 
  # test should be specified as a url or as a hash of the form
  # {:url => "url", :testcases => "testFoo,testBar"}
  def run(test)
    @tests<<test
  end
 
  def browser(browser)
    browser =
      case(browser)
        when :firefox
          FirefoxBrowser.new
        when :safari
          SafariBrowser.new
        when :ie
          IEBrowser.new
        when :konqueror
          KonquerorBrowser.new
        when :opera
          OperaBrowser.new
        else
          browser
      end
 
    @browsers<<browser
  end
end