Class: Oats::TestCase

Inherits:
Object
  • Object
show all
Defined in:
lib/oats/test_case.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(test_file, *args) ⇒ TestCase

Returns a new instance of TestCase.



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/oats/test_case.rb', line 31

def initialize(test_file, *args)
  # Do minimal work here to avoid exception. Raise in run, so that test header appears.
  @id, @is_file, @path, @handler = args.empty? ? TestCase.parse_test_files(test_file) : args
  if args[0].instance_of?(Array)
    @is_file = true
    @path = args[0].shift# Treat as rb below
    @method = args[0].shift
    @id = args[0].shift
    @args = args[0]
  end
  TestList.current.variations.last.tests << self
  @result = nil
  @status = nil
  @errors = []
  @sql_input_error = nil
  @downloaded_files = []
  @start_time = Time.now.to_i
end

Instance Attribute Details

#downloaded_filesObject (readonly)

Array containing names of the downloded files during the test



27
28
29
# File 'lib/oats/test_case.rb', line 27

def downloaded_files
  @downloaded_files
end

#end_timeObject

Time object referring to the end time of the test.



23
24
25
# File 'lib/oats/test_case.rb', line 23

def end_time
  @end_time
end

#error_capture_fileObject

System capture sets this to the name of last error file if one is created



29
30
31
# File 'lib/oats/test_case.rb', line 29

def error_capture_file
  @error_capture_file
end

#errorsObject (readonly)

List of exceptions encountered on the test so far



19
20
21
# File 'lib/oats/test_case.rb', line 19

def errors
  @errors
end

#handlerObject (readonly)

Path of handler defined by Oats.data <<:is_file>_extension>_handler



11
12
13
# File 'lib/oats/test_case.rb', line 11

def handler
  @handler
end

#idObject (readonly)

Path of test relative to the dir_tests library



13
14
15
# File 'lib/oats/test_case.rb', line 13

def id
  @id
end

#is_fileObject (readonly)

extension of the test if it is a single rb file instead of a directory



9
10
11
# File 'lib/oats/test_case.rb', line 9

def is_file
  @is_file
end

#pathObject (readonly)

Absolute path of the test



7
8
9
# File 'lib/oats/test_case.rb', line 7

def path
  @path
end

#resultObject (readonly)

Output result directory



17
18
19
# File 'lib/oats/test_case.rb', line 17

def result
  @result
end

#start_timeObject (readonly)

Time object referring to the start time of the test.



25
26
27
# File 'lib/oats/test_case.rb', line 25

def start_time
  @start_time
end

#statusObject

Current status of the test 0:pass, 1:fail, 2:skip



21
22
23
# File 'lib/oats/test_case.rb', line 21

def status
  @status
end

#typeObject

Type of last executed rtest file 1:rb, 2:ide, 3:sql, 0: post, 4: pre



15
16
17
# File 'lib/oats/test_case.rb', line 15

def type
  @type
end

Class Method Details

.backtrace(obj = nil) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/oats/test_case.rb', line 95

def TestCase.backtrace(obj=nil)
  obj ||= $!
  return unless obj.kind_of? Exception
  filtered = obj.backtrace
  filtered = obj.backtrace.delete_if { |line| line !~ /[\/|\\]oats\/tests[\/|\\]/} unless $oats['execution']['full_stacktrace']
  # Doing below only filters the message in the log, not the full backtrace in the results.dump
  #    unless $oats['execution']['full_stacktrace']
  #      filtered = obj.backtrace.delete_if { |line| line !~ /[\/|\\]oats\/tests[\/|\\]/}
  #      if TestCase.respond_to?('backtrace_filter')
  #        new_filtered = []
  #        filtered.each { |line| new_filtered << TestCase.backtrace_filter(line) }
  #        filtered = new_filtered
  #      end
  #    end
  return "Caught #{obj.class}: #{obj.message}" + ( filtered.empty? ? '' : "\n\t") + filtered.join("\n\t")
end

.locate_test_rb(ruby_file_name) ⇒ Object



474
475
476
477
478
# File 'lib/oats/test_case.rb', line 474

def TestCase.locate_test_rb(ruby_file_name)
  file = ruby_file_name.sub(/\..*/,'')
  file = File.join( $oats['execution']['dir_tests'],'/**/', file+'.rb')
  Dir.glob(file).first
end

.parse_test_files(test_file) ⇒ Object



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
# File 'lib/oats/test_case.rb', line 50

def TestCase.parse_test_files(test_file)
  extension = File.extname(test_file)[1..-1]
  handler = $oats['execution'][extension+'_handler'] if extension
  if handler
    handler_located = TestData.locate(handler)
    Oats.assert handler_located, "Could not find handler file #{handler}"
    handler = handler_located
  end
  if extension == 'xlw'
    id  = test_file.sub(/\.#{extension}\z/,'')
    test_file = File.join(File.dirname(File.dirname(test_file)), File.basename(test_file,extension) + 'xls')
  end
  path = TestData.locate(test_file,true)
  unless path
    unless handler
      path = File.join($oats['execution']['dir_tests'], test_file)
      if 'xltest' == extension
        test_file.sub!(/\.#{extension}\z/,'')
      else
        path = nil
      end
      return test_file, extension, path, handler
    end
    test_dir = File.dirname(test_file)
    if test_dir == '.'
      path = File.join(File.dirname(handler),File.basename(test_file))
    else
      test_dir = TestData.locate(test_dir, true)
      return test_file, extension, path, handler unless test_dir
      path = File.join(test_dir,File.basename(test_file))
    end
    remove_extension = true
  end
  extension ||= File.extname(path)[1..-1]  # In case of implied extensions
  unless id
    id = path.sub( Regexp.new( '^' + $oats['execution']['dir_tests'] + '/', Regexp::IGNORECASE ) , '')
    id.sub!(/\.#{extension}\z/,'') unless remove_extension
  end
  return id, extension, path, handler
end

Instance Method Details

#backtrace(obj = nil) ⇒ Object



91
92
93
# File 'lib/oats/test_case.rb', line 91

def backtrace(obj=nil)
  TestCase.backtrace(obj)
end

#nameObject

Basename of test.dir



481
482
483
484
# File 'lib/oats/test_case.rb', line 481

def name
  return @name if @name
  @name = File.basename(@id)
end

#okObject

Directory of expected results, manually checked in to code repository under test.dir

Raises:



493
494
495
496
497
498
499
500
501
# File 'lib/oats/test_case.rb', line 493

def ok
  return @ok if @ok
  raise OatsError, "Test [#{self.id}] does not have a directory" unless @path
  if @is_file
    @ok = @path + '_ok'
  else
    @ok = File.join(@path, 'ok')
  end if @path
end

#ok_outObject

Directory under test.ok, contains expected result output files



504
505
506
507
# File 'lib/oats/test_case.rb', line 504

def ok_out
  return @ok_out if @ok_out
  @ok_out = File.join(self.ok,'out')
end

#outObject

Directory under test.result, contains output files to be compared



487
488
489
490
# File 'lib/oats/test_case.rb', line 487

def out
  return @out if @out
  @out = File.join(self.result, 'out')
end

#runObject



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
# File 'lib/oats/test_case.rb', line 112

def run
  if @type == 0 or @type == 4

    $log.info "*** #{@type == 0 ? 'POST':'PRE'} TEST LIST HANDLER [#{@id}] at #{Time.at(@start_time)}"
  else
    $log.info "*** TEST [#{@id}] at #{Time.at(@start_time)}"
  end
  unless @path
    TestData.error Exception.new("Found no #{@id} file"+
        ((@is_file and !%w(rb sql html).include?(@is_file)) ? " nor handler for #{@is_file.inspect}." : ".")
    )
    return
  end
  if @is_file
    if !%w(rb sql html xltest).include?(@is_file) and !@handler
      TestData.error Exception.new("Unrecognized extension #{@is_file} for test file [#{@path}]")
      return
    end
  else
    unless FileTest.directory?(@path)
      TestData.error Exception.new("Test file must have extension")
      return
    end
  end
  if @is_file
    oats_file = @path.sub(/\.#{@is_file}\z/,'.yml')
    yaml_dir = File.dirname(@path) unless File.exist?(oats_file)
  else
    test_var_dir = File.join(@path,'environments')
    oats_files = Dir.glob(File.join(@path,'*.yml'))
    if oats_files.size == 1
      oats_file = oats_files.first
    else
      yaml_dir = @path
    end
  end
  if yaml_dir
    oats_file = File.join(yaml_dir,'oats.yml')
    oats_file = nil unless File.exist?(oats_file)
  end
  odat = nil
  if @is_file == 'xltest'
    pth = @id.split('/')
    pth.pop
    suit = pth.pop
    $oats_global['xl'][@id]['data']['keywords'] = $oats_global['xl'][@id]['keywords']
    odat = { pth.pop => { 'list' => suit, suit => $oats_global['xl'][@id]['data'] } }
  end
  $oats = OatsData.overlay(odat) if odat
  $oats = OatsData.overlay(oats_file) if oats_file
  if test_var_dir and File.directory?(test_var_dir)
    vars_overlayed = []
    $oats['_']['environments'].each do |var_file|
      ## Overlay all previously introduced variations, but only once
      var_name = File.basename(var_file,'.*')
      test_var = File.join(test_var_dir,var_name+'.yml')
      if File.exist?(test_var) and not vars_overlayed.include?(var_name)
        $oats = OatsData.overlay(test_var)
        vars_overlayed << var_name
      end
    end
  end

  $log.debug 'Effective config file history: ' + OatsData.history[1..-1].inspect

  if $oats['execution']['dir_results']
    FileUtils.mkdir_p($oats['execution']['dir_results']) unless File.directory?($oats['execution']['dir_results'])
    result_root = Util.expand_path(id, $oats['execution']['dir_results'])
  else
    result_root = File.join(@is_file ? File.dirname(@path) : @path,'result')
  end
  hist_path = OatsData.history(true)
  if hist_path.empty?
    result_dir = result_root
  else
    result_dir = File.join( result_root,
      hist_path[1..-1].collect{|f|File.basename(f , '.*')}.join('/'))
  end
  if $oats['execution']['no_run'] # Reuse the last timestamped result_dir
    if File.directory?(result_dir)
      latest = Dir.entries(result_dir).last
      result_dir = File.join(result_dir,latest)
    else
      result_dir_save =  result_dir
      result_dir = nil
    end
  else
    #      result_dir = File.join(result_dir, @start_time.to_s[2..-1] ) # Create a new timestamped sub result_dir
    FileUtils.mkdir_p(result_dir)
  end
  @result = result_dir
  if result_dir
    test_log = File.join(result_dir,'oats_test.log')
    Log4r::FileOutputter.new('test_log',
      :filename=>test_log, :trunc=>false,  # :level=>level + 1)
      :formatter=>Log4r::PatternFormatter.new(:depth=>50,
        :pattern => "%-5l %d %M", :date_pattern=>"%y-%m-%d %H:%M:%S"))
    $log.add('test_log')
  end
  if $oats['execution']['no_run']
    @status = 2
    msg =  $oats['execution']['no_run'].instance_of?(String) ? (' to '+$oats['execution']['no_run'].inspect) : ''
    $log.warn "Skipping execution since execution:no_run is set#{msg}."
    return
  end
  # Clean download directory
  if $oats_global['download_dir']
    files = Dir.glob(File.join($oats_global['download_dir'],'*'))
    FileUtils.rm(files) unless files.empty?
  end
  # Initialize classes this test may need
  #    $ide = Ide.new unless ENV['JRUBY_BASE']
  # Execute the test
  ApplicationLogs.new_errors(true) # Reset pre-existing errors
  if @is_file
    oats_tsts = [ @handler || @path ]
  else
    oats_tsts = Dir[File.join(@path,'rtest*.{rb,html,sql}')].delete_if { |e| /\.gen\./ =~ e }
    oats_tsts.unshift(root + '.html') if File.exist?(@path + '.html') # Compatibility with older tests
    oats_tsts = Dir[File.join(@path,'*.{rb,html,sql}')] if oats_tsts.empty?
    raise(OatsError,"No files matching rtest*.{rb,html,sql} found in: #{@path}") if oats_tsts.empty?
  end
  if result_dir and Oats.data['execution']['run_in_dir_results']
    unless @is_file
      Dir.glob(File.join(@path,'*')).each do |file|
        FileUtils.cp(file, result_dir ) if File.file?(file)
      end
    end
    run_dir = result_dir
  else
    raise(OatsError,"Can not run single rb file test without a result_dir.") if @is_file
    run_dir = @path
  end
  quit_on_error = $oats['execution']['quit_on_error']
  skip_unless_previous_test_is_ok = $oats['execution']['skip_unless_previous_test_is_ok']
  Oats.global['rbtests'] = []
  Dir.chdir(run_dir) do
    begin
      oats_tsts.sort!
      oload_hooks(oats_tsts, 'pre', 'unshift')
      oload_hooks(oats_tsts, 'post', 'push')
      #        FileUtils.mkdir_p(out)
      exception_in_rb = false
      oats_tsts.each do |rt|
        break if quit_on_error and not errors.empty?
        if skip_unless_previous_test_is_ok and TestData.previous_test and TestData.previous_test.status != 0
          $oats['execution']['no_run'] = true
          Oats.info "Skipping due to previous test failure"
        end
        raise(OatsError,"Can not read file [#{rt}]") unless File.readable?(rt) unless @is_file == 'xltest'
        begin
          case @is_file
          when 'html'
            Oats.ide(rt)
          when 'sql'
            Oats.mysql(rt)
          when /^rb$||^xltest$/
            begin
              if @method
                $log.info "Executing OatsTest:#{@method}"
                Oats.global['rbtests'] << rt # Not sure if this is needed
                Oats.global['oloads'] = []  # Not sure if this is needed
                exception_in_rb = true
                OatsTest.send(@method,*@args)
                exception_in_rb = false
              else
                next if exception_in_rb # Don't process a second rb if one throws an exception
                Oats.global['rbtests'] << rt
                Oats.global['oloads'] = []
                exception_in_rb = true
                if @is_file == 'xltest'
                  $log.info "Processing test: #{rt}"
                  Oats::Keywords.process
                else
                  $log.info "Processing rb file: #{rt}"
                  load(rt,true)
                end
                exception_in_rb = false
              end
            rescue OatsTestExit # Regular exit from the rb test
              message = $!.message
              $log.info message unless message == 'OatsTestExit'
            rescue Exception => e
              case e
              when OatsError, Timeout::Error then $log.error backtrace($!)
              else $log.error $! # Full stackstrace
              end
              TestData.error($!)
              Oats.system_capture unless Oats.data['selenium']['skip_capture']
            ensure
              Oselenium.pause_browser if defined?(Oats::Oselenium)
            end
          else
            raise OatsError, "Unrecognized test extension #{@is_file}"
          end
        rescue OatsMysqlNoConnect
          @sql_input_error = true
          @status = 2
          $log.warn "#{$!}. Test is classified as SKIPPED."
        rescue OatsError # No stack for known errors from rmsql and ide
          $log.error $!.to_s
          TestData.error($!)
        rescue # Otherwise want the stack trace
          $log.error TestCase.backtrace($!)
        end
      end
    ensure
      begin
        $mysql.processlist if timed_out?  # Ensure selenium closes if this throws an exception
      rescue
      end
      Oselenium.reset if defined?(Oats::Oselenium) and ($oats['selenium']['keep_alive'].nil? or ! errors.empty?)
      FileUtils.rm_rf(out) if File.directory?(out) and
        Dir.glob(File.join(out,'*')).empty?
      if $oats['execution']['no_run']
        $log.warn "Classifying test as SKIPPED since execution:no_run is set"
        @status = 2
        return
      end
    end
  end # of the out generation phase

  # Verify phase
  if result_dir
    verify
  else
    $log.warn "Skipping verification, can not find result directory: #{result_dir_save}"
  end
  log_errors = ApplicationLogs.new_errors
  unless log_errors.empty?
    log_errors.each {|e| $log.error e.chomp }
    raise(OatsVerifyError,"Found errors in the application logs.")
  end
  if errors.empty?
    @status = 0 unless @status
    FileUtils.rm Dir[File.join( Oats.data['execution']['run_in_dir_results'] ? result_dir : dir ,'*.gen.*')]  \
      if result_dir and not Oats.data['selenium']['ide']['keep_generated_files']
  end
end

#timed_out?Boolean

Returns:

  • (Boolean)


376
377
378
379
380
381
382
# File 'lib/oats/test_case.rb', line 376

def timed_out?
  @errors.each do |exc|
    # $log.info exc # debug
    return true if exc[0] == 'Timeout::Error'
  end
  return false
end