-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRakefile
executable file
·558 lines (518 loc) · 21.9 KB
/
Rakefile
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
# Copyright (C) 2010 Alexandre Berman, Lazybear Consulting ([email protected])
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
# -- usage: rake help
require 'net/pop'
require 'net/smtp'
require 'net/http'
require 'uri'
require 'tlsmail'
require "timeout"
require "fileutils"
require "yaml"
# -- global vars
task :default => [:run]
@suite_root = File.expand_path "#{File.dirname(__FILE__)}"
@rake_env_file = "#{@suite_root}/rake.env.yaml"
@rake_env_user_file = "#{@suite_root}/user.rake.env.yaml"
@tests = []
@tests_retried_counter = 0
@executed_tests = 0
@reports_dir = ENV['HOME'] + "/rake_reports" # -- default
@reports_dir = ENV['REPORTS_DIR'] if ENV['REPORTS_DIR'] != nil
ENV["REPORTS_DIR"] = @reports_dir
#
# -- the following vars control the behavior of running tests: default values
@test_data = {
'output_on' => false,
'test_retry' => 0,
'test_exit_message_passed' => "PASSED",
'test_exit_message_failed' => "FAILED",
'test_exit_message_skipped' => "SKIPPED",
'xml_report_class_name' => "qa.tests",
'xml_report_file_name' => "TESTS-TestSuites.xml",
'interpreter' => "ruby",
'test_extension' => ".rb",
'excludes' => ".svn",
'test_dir' => "tests",
'test_timeout' => 1200, # -- miliseconds
# -- mail related vars
'pop_host' => "pop.gmail.com",
'pop_port' => 995,
'smtp_host' => "smtp.gmail.com",
'smtp_port' => 587,
'mail_domain' => "gmail.com",
'user_name' => "",
'user_passwd' => "",
'reply_email' => "",
'use_jenkins' => false,
'jenkins_job_url' => "",
'jenkins_job_parameter' => "",
'two_step_authentication' => false
}
# *************************** BEGIN SETUP ***************************
# -- write out test data hash into a YAML file to hold basic ZONT environment
def write(filename, hash)
File.open(filename, "w") { |f| f.write(hash.to_yaml) }
end
# -- if 'rake.env.yaml' exists, load values from there into @test_data hash; otherwise write defaults to newly created 'rake.env.yaml' file.
if File.exist?(@rake_env_file)
@test_data.merge!(YAML::load(File.read(@rake_env_file)))
else
puts "\n\n-- INFO: {#{@rake_env_file}} doesn't exist, it will be created with default values.\n\n"
write(@rake_env_file, @test_data)
end
# -- loading user-defined properties from yaml: if 'user.rake.env.yaml' file exists, we'll use it to overwrite @test_data hash
if File.exist?(@rake_env_user_file)
YAML::load(File.read(@rake_env_user_file)).each_pair { |key, value|
@test_data[key] = value if @test_data[key] != nil
}
end
# -- merge any other variables that we don't want to be stored in the 'rake.env' file into @test_data hash
@test_data.merge!({'reports_dir' => @reports_dir})
# *************************** END SETUP ***************************
# -- usage
desc "-- usage"
task :help do
puts "\n-- usage: \n\n"
puts " rake help : print this message"
puts " rake : this will by default run :run task, which runs all tests"
puts " rake run KEYWORDS=<keyword1,keyword2> : this will run tests based on keyword"
puts " rake print_human : this will print descriptions of your tests"
puts " rake print_human KEYWORDS=<keyword1,keyword2> : same as above, but only for tests corresponding to KEYWORDS"
puts " rake REPORTS_DIR=</path/to/reports> : this will set default reports dir and run all tests"
puts " rake mail_gateway : this will activate email remote control which will listen for remote commands"
puts " rake mail_gateway_help : prints basic help for using email remote control\n\n"
puts " Eg:\n\n rake KEYWORDS=<keyword1, keyword2> REPORTS_DIR=/somewhere/path\n\n\n"
puts " Sample comments in your tests (eg: tests/some_test.rb):\n\n"
puts " # @author Alexandre Berman"
puts " # @executeArgs"
puts " # @keywords acceptance"
puts " # @description some interesting test\n\n"
puts " Note 1:\n\n Your test must end with 'test.rb' - otherwise Rake won't be able to find it, eg:\n"
puts " tests/some_new_test.rb\n\n"
puts " Note 2:\n\n Your test must define at least one keyword.\n\n\n"
puts " 'rake.yaml' file will be created (if it doesn't already exist) with default values controlling behavior of Rake.\n\n\n"
end
# -- mail gateway usage
def mail_help
xxx = "-- Following messages are supported: \n\n"
xxx += " '==help==' system will reply with this message\n"
xxx += " '==list==' system will reply with list of available programs\n"
xxx += " '==play <KEYWORD>==' system will run a program specified by 'KEYWORD'\n\n"
return xxx
end
# -- mail gateway usage
desc "-- mail gateway usage"
task :mail_gateway_help do
puts mail_help
end
# -- prepare reports_dir
def prepare_reports_dir
FileUtils.rm_r(@test_data['reports_dir']) if File.directory?(@test_data['reports_dir'])
FileUtils.mkdir_p(@test_data['reports_dir'])
end
# -- our own each method yielding each test in the @tests array
def each
@tests.each { |t| yield t }
end
# -- filtering by keywords
def filter_by_keywords
# -- do we have keywords set ?
if (ENV['KEYWORDS'] != nil and ENV['KEYWORDS'].length > 0)
tmp_tests = []
# -- loop through all keywords
ENV['KEYWORDS'].gsub(/,/, ' ').split.each { |keyword|
# -- loop through all tests
@tests.each { |t|
# -- loop through all keywords for a given test
t.keywords.each { |k|
if k == keyword
tmp_tests << t
end
}
}
}
# -- in case only a negative keyword was given, let's fill up tmp_tests array here (ie: if it is empty now):
tmp_tests = @tests.uniq if tmp_tests.length < 1 and /!/.match(ENV['KEYWORDS'])
# -- check for a negative keyword
if /!/.match(ENV['KEYWORDS'])
ENV['KEYWORDS'].gsub(/,/, ' ').split.each { |keyword|
if /!/.match(keyword)
keyword.gsub!(/!/, '')
# -- loop through all tests
@tests.each { |t|
# -- loop through all keywords for a given test
t.keywords.each { |k|
# -- if keyword matches with negative keyword, remove this test from the array
if k == keyword
tmp_tests.delete(t)
end
}
}
end
}
end
# -- replace original @tests with tmp_tests array
@tests = tmp_tests.uniq
end
end
# -- load test: populate a hash with right entries and create a Test object for it
def load_test(tc)
data = Hash.new
File.open(tc, "r") do |infile|
while (line = infile.gets)
#test = /^.*\/(.*\.rb)/.match(tc)[1]
test = /^.*\/([A-Za-z0-9_-]*[T|t]est.*)/.match(tc)[1]
data['execute_class'] = /^([A-Za-z0-9_-]*[T|t]est.*)/.match(tc)[1]
data['path'] = /(.*)\/#{test}/.match(tc)[1]
data['execute_args'] = /^#[\s]*@executeArgs[\s]*(.*)/.match(line)[1] if /^#[\s]*@executeArgs/.match(line)
data['author'] = /^#[\s]*@author[\s]*(.*)/.match(line)[1] if /^#[\s]*@author/.match(line)
data['keywords'] = /^#[\s]*@keywords[\s]*(.*)/.match(line)[1].gsub(/,/,'').split if /^#[\s]*@keywords/.match(line)
data['description'] = /^#[\s]*@description[\s]*(.*)/.match(line)[1] if /^#[\s]*@description/.match(line)
end
end
@tests << Test.new(data, @test_data) if data['keywords'] != nil and data['keywords'] != ""
end
# -- find tests and load them one by one, applying keyword-filter at the end
desc "-- find all tests..."
task :find_all do
FileList["#{@test_data['test_dir']}/**/*[T|t]est#{@test_data['test_extension']}"].exclude(@test_data['excludes']).each { |tc_name|
load_test(tc_name)
}
filter_by_keywords
end
# -- BEGIN EMAIL GATEWAY RELATED CODE
# -- do_reply
def do_reply(subject, msg)
full_msg=<<END_OF_MESSAGE
From: #{@test_data['user_name']}
To: #{@test_data['reply_email']}
Subject: #{subject}
Date: #{Time.now}
#{msg}
END_OF_MESSAGE
Net::SMTP.enable_tls(OpenSSL::SSL::VERIFY_NONE)
Net::SMTP.start(@test_data['smtp_host'], @test_data['smtp_port'], @test_data['mail_domain'], @test_data['user_name'], @test_data['user_passwd'], :login) { |smtp|
smtp.send_message(full_msg, @test_data['user_name'], @test_data['reply_email'])
}
end
# -- play received request
def play_request(keyword)
# -- we either execute program marked by received keyword directly, or trigger Jenkins build
if @test_data['use_jenkins']
url = @test_data['jenkins_job_url'] + @test_data['jenkins_job_parameter'] + "=" + keyword
Net::HTTP.get(URI.parse("#{url}"))
xxx = "-- Jenkins job was invoked with supplied parameter: " + keyword + "\n\n-- url: " + url
do_reply("-- Jenkins job invoked", xxx)
else
xxx = "-- executing: rake KEYWORDS='" + keyword + "'\n\n"
xxx += `rake KEYWORDS='#{keyword}'`
do_reply("-- status of playback delivered", xxx)
end
end
# -- two_step_authenticate: send random number to reply_to email
def authentication_send_code(keyword)
# -- first: save received keyword with the code for later matching
code = rand(50000).to_s
file = @suite_root + "/" + code + ".au"
File.open(file, "w") { |f| f.write(keyword) }
# -- then: send random code for authentication
do_reply("-- authenticate yourself by replying to this email", "==authentication: #{code}==")
end
# -- two_step_authenticate: process received code and match with what was sent
def authentication_process_code(code)
# -- match received code against a file with same name: its content should be the keyword to play
# if file doesn't exist, then we just ignore the whole thing - that means authentication failed !
file = @suite_root + "/" + code + ".au"
if File.exist?(file)
keyword = File.open(file, 'r') { |f| f.read }
File.delete(file)
play_request(keyword)
end
end
# -- pop mail
def pop_mail
Net::POP3.enable_ssl(OpenSSL::SSL::VERIFY_NONE)
Net::POP3.start(@test_data['pop_host'], @test_data['pop_port'], @test_data['user_name'], @test_data['user_passwd']) do |pop|
if pop.mails.empty?
puts("-- no mail.")
else
pop.each_mail do |m|
puts("-- >>> processing new message ...")
msg = m.pop
# -- is the message one that we expect and know how to handle ?
if !/==.*==/.match(msg)
do_reply("-- ERROR: wrong argument supplied !", mail_help)
else
# -- ok, this message is for us
msg = /^(.*)(==.*==).*$/.match(msg)[2].gsub(/==/, '').strip
case msg
when /help/
do_reply("-- Help on using mail interface delivered !", mail_help)
when /list/
xxx = `rake print_human`
do_reply("-- list of objects delivered !", xxx)
when /play\s+.*$/
keyword = msg.gsub(/play/, '').strip
# -- do we have two-step-authentication enabled ?
if @test_data['two_step_authentication']
authentication_send_code(keyword)
else
play_request(keyword)
end
when /authentication:\s+.*$/
code = msg.gsub(/authentication:/, '').strip
authentication_process_code(code)
end
end
m.delete
puts "-- >>> done ..."
end
end
end
end
# -- start mail gateway
desc "-- start mail gateway..."
task :mail_gateway do
pop_mail
end
# -- END EMAIL GATEWAY RELATED CODE
# -- print tests
desc "-- print tests..."
task :print_human do
Rake::Task["find_all"].invoke
each { |t|
begin
puts t.to_s
rescue => e
puts "-- ERROR: " + e.inspect
puts " (in test: #{t.execute_class})"
end
}
end
# -- run all tests
desc "-- run all tests..."
task :run do
# -- first, let's setup/cleanup reports_dir
prepare_reports_dir
# -- now, find all tests
Rake::Task["find_all"].invoke
tStart = Time.now
# -- let's run each test now
each { |t|
begin
t.validate
# -- do we run test more than once if it failed first time ?
if (t.exit_status == @test_data['test_exit_message_failed']) and (@test_data['test_retry'] > 0)
puts("-- first attempt failed, will try again for a total of {#{@test_data['test_retry']}} number of times...")
retried_counter = 0
@tests_retried_counter += 1
while(retried_counter < @test_data['test_retry'])
puts("-- {#{@test_data['test_retry'] - retried_counter}} number of attempts left...")
retried_counter += 1
t.validate
retried_counter = @test_data['test_retry'] if t.exit_status == @test_data['test_exit_message_passed']
end
end
rescue => e
puts "-- ERROR: " + e.inspect
puts " (in test: #{t.execute_class})"
ensure
@executed_tests += 1
end
}
tFinish = Time.now
@execution_time = tFinish - tStart
clean_exit
end
# -- total by exit status
def all_by_exit_status(status)
a = Array.new
each { |t|
a << t if t.exit_status == status
}
return a
end
# -- what do we do on exit ?
def clean_exit
passed = all_by_exit_status(@test_data['test_exit_message_passed'])
failed = all_by_exit_status(@test_data['test_exit_message_failed'])
skipped = all_by_exit_status(@test_data['test_exit_message_skipped'])
@test_data.merge!({'execution_time' => @execution_time, 'passed' => passed, 'failed' => failed, 'skipped' => skipped})
Publisher.new(@test_data).publish_reports
puts("\n==> DONE\n\n")
puts(" -- execution time : #{@execution_time.to_s} secs\n")
puts(" -- tests executed : #{@executed_tests.to_s}\n")
puts(" -- reports prepared: #{@test_data['reports_dir']}\n")
puts(" -- tests passed : #{passed.length.to_s}\n")
puts(" -- tests failed : #{failed.length.to_s}\n")
puts(" -- tests skipped : #{skipped.length.to_s}\n")
if (@test_data['test_retry'] > 0)
puts(" -- tests re-tried : #{@tests_retried_counter.to_s}\n")
end
if failed.length > 0
puts("\n\n==> STATUS: [ some tests failed - execution failed ]\n")
exit(1)
end
exit(0)
end
#
# ::: Publisher [ creating report files ] :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
class Publisher
def initialize(test_data)
@test_data = test_data
@total = @test_data['passed'].length + @test_data['failed'].length + @test_data['skipped'].length
end
def write_file(file, data)
File.open(file, 'w') {|f| f.write(data) }
end
def create_html_reports(status)
output = "<html><body>\n\nTests that #{status}:<br><br><table><tr><td>test</td><td>time</td></tr><tr></tr>\n"
@test_data[status].each { |t|
output += "<tr><td><a href='#{t.execute_class}.html'>#{t.execute_class}</a></td><td>#{t.execution_time}</td></tr>\n"
}
output += "</table></body></html>"
write_file(@test_data['reports_dir'] + "/#{status}.html", output)
end
def publish_reports
# -- remove reports dir if it exists, then create it
# -- create an xml file
document = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
document += "<testsuites>\n"
document += " <testsuite successes='#{@test_data['passed'].length}'"
document += " skipped='#{@test_data['skipped'].length}' failures='#{@test_data['failed'].length}'"
document += " time='#{@test_data['execution_time']}' name='FunctionalTestSuite' tests='#{@total}'>\n"
if @test_data['passed'].length > 0
@test_data['passed'].each { |t|
document += " <testcase name='#{t.execute_class}' classname='#{@test_data['xml_report_class_name']}' time='#{t.execution_time}'>\n"
document += " <passed message='Test Passed'><![CDATA[\n\n#{t.output}\n\n]]>\n </passed>\n"
document += " </testcase>\n"
}
end
if @test_data['failed'].length > 0
@test_data['failed'].each { |t|
document += " <testcase name='#{t.execute_class}' classname='#{@test_data['xml_report_class_name']}' time='#{t.execution_time}'>\n"
document += " <error message='Test Failed'><![CDATA[\n\n#{t.output}\n\n]]>\n </error>\n"
document += " </testcase>\n"
}
end
if @test_data['skipped'].length > 0
@test_data['skipped'].each { |t|
document += " <testcase name='#{t.execute_class}' classname='#{@test_data['xml_report_class_name']}' time='#{t.execution_time}'>\n"
document += " <skipped message='Test Skipped'><![CDATA[\n\n#{t.output}\n\n]]>\n </skipped>\n"
document += " </testcase>\n"
}
end
document += " </testsuite>\n"
document += "</testsuites>\n"
# -- write XML report
write_file(@test_data['reports_dir'] + "/" + @test_data['xml_report_file_name'], document)
# -- write HTML report
totals = "<html><body>\n\nTotal tests: #{@total.to_s}<br>\n"
totals += "Passed: <a href='passed.html'>#{@test_data['passed'].length.to_s}</a><br>\n"
totals += "Failed: <a href='failed.html'>#{@test_data['failed'].length.to_s}</a><br>\n"
totals += "Skipped: <a href='skipped.html'>#{@test_data['skipped'].length.to_s}</a><br>\n"
totals += "Execution time: #{@test_data['execution_time']}<br>\n</body></html>"
write_file(@test_data['reports_dir'] + "/report.html", totals)
# -- create individual html report files complete with test output
create_html_reports("passed")
create_html_reports("failed")
create_html_reports("skipped")
end
end
#
# ::: Test class [ running a test ] :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
class Test
attr_accessor :path, :execute_class, :execute_args, :keywords, :description, :author,
:exit_status, :output, :execution_time, :test_data
def initialize(hash, test_data)
@exit_status = @output = @path = @execute_class = @execute_args = @keywords = @description = @author = ""
@test_data = test_data
@execution_time = 0.0
@timeout = @test_data['test_timeout']
@path = hash['path']
@execute_class = hash['execute_class']
@execute_args = hash['execute_args']
@keywords = hash['keywords']
@description = hash['description']
@author = hash['author']
@cmd = @execute_class
end
# -- we should do something useful here
def is_valid
return true
end
def validate
if is_valid
# -- run the test if its valid
run
# -- write entire test output into its own log file
write_log
else
# -- skipping this test
@exit_status = @test_data['test_exit_message_skipped']
end
end
def write_file(file, data)
File.open(file, 'w') {|f| f.write(data) }
end
def write_log
d = /^(.*\/).*/.match(@execute_class)[1]
FileUtils.mkdir_p(@test_data['reports_dir'] + "/#{d}")
write_file(@test_data['reports_dir'] + "/#{@execute_class}.html", "<html><body><pre>" + @output + "</pre></body></html>")
end
def run
@cmd = @cmd + " " + @execute_args unless @execute_args == ""
tStart = Time.now
print("-- #{tStart.strftime('[%H:%M:%S]')} running: [#{@cmd}] ")
begin
status = Timeout::timeout(@timeout.to_i) {
@output = `#{@test_data['interpreter']} #{@cmd} 2>&1`
@exit_status = case @output
when /#{@test_data['test_exit_message_passed']}/ then @test_data['test_exit_message_passed']
when /#{@test_data['test_exit_message_failed']}/ then @test_data['test_exit_message_failed']
else @test_data['test_exit_message_failed']
end
}
rescue Timeout::Error => e
@output << "\n\n[ TERMINATED WITH TIMEOUT (#{@timeout.to_s}) ]"
@exit_status = @test_data['test_exit_message_failed']
ensure
puts @exit_status
puts @output if @test_data['output_on']
end
tFinish = Time.now
@execution_time = tFinish - tStart
end
def to_s
s = "\n path: " + @path + "\n"
if @author != nil
s += " author " + @author + "\n"
end
s += " execute_class " + @execute_class + "\n"
s += " execute_args " + @execute_args + "\n"
s += " keywords " + @keywords.join(',') + "\n"
s += " description " + @description + "\n"
s += " exit_status " + @exit_status.to_s + "\n"
s += " output " + @output + "\n"
s += " execution_time " + @execution_time.to_s + "\n\n"
return s
end
end