generate_test_runner.rb 12.2 KB
Newer Older
1 2 3 4 5 6
# ==========================================
#   Unity Project - A Test Framework for C
#   Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams
#   [Released under MIT License. Please refer to license.txt for details]
# ========================================== 

7
File.expand_path(File.join(File.dirname(__FILE__),'colour_prompt'))
8 9 10

class UnityTestRunnerGenerator

11
  def initialize(options = nil)
12
    @options = { :includes => [], :plugins => [], :framework => :unity }
13 14
    case(options)
      when NilClass then @options
15 16
      when String   then @options.merge!(UnityTestRunnerGenerator.grab_config(options))
      when Hash     then @options.merge!(options)
17 18 19 20
      else          raise "If you specify arguments, it should be a filename or a hash of options"
    end
  end
  
M
mkarlesky 已提交
21
  def self.grab_config(config_file)
22
    options = { :includes => [], :plugins => [], :framework => :unity }
23 24
    unless (config_file.nil? or config_file.empty?)
      require 'yaml'
25
      yaml_guts = YAML.load_file(config_file)
26 27
      options.merge!(yaml_guts[:unity] ? yaml_guts[:unity] : yaml_guts[:cmock])
      raise "No :unity or :cmock section found in #{config_file}" unless options
28
    end
29
    return(options)
30 31
  end

32
  def run(input_file, output_file, options=nil)
33
    tests = []
34
    testfile_includes = []
35 36
    used_mocks = []
    
37
    @options.merge!(options) unless options.nil?
38 39
    module_name = File.basename(input_file)
    
40
    #pull required data from source file
41
    File.open(input_file, 'r') do |input|
42 43 44
      tests               = find_tests(input)
      testfile_includes   = find_includes(input)
      used_mocks          = find_mocks(testfile_includes)
45 46
    end

47
    #build runner file
S
shellyniz 已提交
48
    generate(input_file, output_file, tests, used_mocks, testfile_includes)
49 50 51
    
    #determine which files were used to return them
    all_files_used = [input_file, output_file]
52
    all_files_used += testfile_includes.map {|filename| filename + '.c'} unless testfile_includes.empty?
53 54 55 56
    all_files_used += @options[:includes] unless @options[:includes].empty?
    return all_files_used.uniq
  end
  
S
shellyniz 已提交
57
  def generate(input_file, output_file, tests, used_mocks, testfile_includes)
58
    File.open(output_file, 'w') do |output|
S
shellyniz 已提交
59
      create_header(output, used_mocks, testfile_includes)
60 61
      create_externs(output, tests, used_mocks)
      create_mock_management(output, used_mocks)
62
      create_suite_setup_and_teardown(output)
63
      create_reset(output, used_mocks)
64
      create_main(output, input_file, tests)
65 66 67 68
    end
  end
  
  def find_tests(input_file)
69
    tests_raw = []
70
    tests_args = []
71 72
    tests_and_line_numbers = []
    
73
    input_file.rewind
74
    source_raw = input_file.read
75 76 77 78
    source_scrubbed = source_raw.gsub(/\/\/.*$/, '')           # remove line comments
    source_scrubbed = source_scrubbed.gsub(/\/\*.*?\*\//m, '') # remove block comments
    lines = source_scrubbed.split(/(^\s*\#.*$)                 # Treat preprocessor directives as a logical line
                              | (;|\{|\}) /x)                  # Match ;, {, and } as end of lines
79 80

    lines.each_with_index do |line, index|
81 82
      #find tests
      if line =~ /^((?:\s*TEST_CASE\s*\(.*?\)\s*)*)\s*void\s+(test.*?)\s*\(\s*(.*)\s*\)/
83
        arguments = $1
84 85
        name = $2
        call = $3
86 87 88 89 90
        args = nil
        if (@options[:use_param_tests] and !arguments.empty?)
          args = []
          arguments.scan(/\s*TEST_CASE\s*\((.*)\)\s*$/) {|a| args << a[0]}
        end
91
        tests_and_line_numbers << { :test => name, :args => args, :call => call, :line_number => 0 }
92
        tests_args = []
93 94 95
      end
    end

96
    #determine line numbers and create tests to run
97 98
    source_lines = source_raw.split("\n")
    source_index = 0;
99
    tests_and_line_numbers.size.times do |i|
100
      source_lines[source_index..-1].each_with_index do |line, index|
101
        if (line =~ /#{tests_and_line_numbers[i][:test]}/)
102
          source_index += index
103
          tests_and_line_numbers[i][:line_number] = source_index + 1
104 105
          break
        end
106 107
      end
    end
108
    
109
    return tests_and_line_numbers
110 111 112 113
  end

  def find_includes(input_file)
    input_file.rewind
114 115 116 117 118 119 120 121 122 123
    
    #read in file
    source = input_file.read
    
    #remove comments (block and line, in three steps to ensure correct precedence)
    source.gsub!(/\/\/(?:.+\/\*|\*(?:$|[^\/])).*$/, '')  # remove line comments that comment out the start of blocks
    source.gsub!(/\/\*.*?\*\//m, '')                     # remove block comments 
    source.gsub!(/\/\/.*$/, '')                          # remove line comments (all that remain)
    
    #parse out includes
S
shellyniz 已提交
124 125 126 127
    includes = source.scan(/^\s*#include\s+\"\s*(.+)\.[hH]\s*\"/).flatten  
	brackets_includes = source.scan(/^\s*#include\s+<\s*(.+)\s*>/).flatten
	brackets_includes.each { |inc| includes << '<' + inc +'>' }		
	return includes
128 129 130 131 132
  end
  
  def find_mocks(includes)
    mock_headers = []
    includes.each do |include_file|
M
mvandervoord 已提交
133
      mock_headers << File.basename(include_file) if (include_file =~ /^mock/i)
134 135 136 137
    end
    return mock_headers  
  end
  
S
shellyniz 已提交
138
  def create_header(output, mocks, testfile_includes)
139
    output.puts('/* AUTOGENERATED FILE. DO NOT EDIT. */')
140 141
    create_runtest(output, mocks)
    output.puts("\n//=======Automagically Detected Files To Include=====")
M
mvandervoord 已提交
142
    output.puts("#include \"#{@options[:framework].to_s}.h\"")
143
    output.puts('#include "cmock.h"') unless (mocks.empty?)
144
    @options[:includes].flatten.uniq.compact.each do |inc|
M
mvandervoord 已提交
145
      output.puts("#include #{inc.include?('<') ? inc : "\"#{inc.gsub('.h','')}.h\""}")
146 147 148
    end
    output.puts('#include <setjmp.h>')
    output.puts('#include <stdio.h>')
149
    output.puts('#include "CException.h"') if @options[:plugins].include?(:cexception)
S
shellyniz 已提交
150 151 152 153 154
	testfile_includes.delete("unity").delete("cmock")
	testrunner_includes = testfile_includes - mocks	
	testrunner_includes.each do |inc|	  
	  output.puts("#include #{inc.include?('<') ? inc : "\"#{inc.gsub('.h','')}.h\""}")	  
	end
155 156 157
    mocks.each do |mock|
      output.puts("#include \"#{mock.gsub('.h','')}.h\"")
    end
158
    if @options[:enforce_strict_ordering]
159
      output.puts('')    
160 161 162 163
      output.puts('int GlobalExpectCount;') 
      output.puts('int GlobalVerifyOrder;') 
      output.puts('char* GlobalOrderError;') 
    end
164 165 166
  end
  
  def create_externs(output, tests, mocks)
167
    output.puts("\n//=======External Functions This Runner Calls=====")
168 169 170
    output.puts("extern void setUp(void);")
    output.puts("extern void tearDown(void);")
    tests.each do |test|
171
      output.puts("extern void #{test[:test]}(#{test[:call] || 'void'});")
172 173 174 175 176 177
    end
    output.puts('')
  end
  
  def create_mock_management(output, mocks)
    unless (mocks.empty?)
178
      output.puts("\n//=======Mock Management=====")
179 180
      output.puts("static void CMock_Init(void)")
      output.puts("{")
181
      if @options[:enforce_strict_ordering]
182 183 184
        output.puts("  GlobalExpectCount = 0;")
        output.puts("  GlobalVerifyOrder = 0;") 
        output.puts("  GlobalOrderError = NULL;") 
185
      end
186
      mocks.each do |mock|
187 188
        mock_clean = mock.gsub(/(?:-|\s+)/, "_")
        output.puts("  #{mock_clean}_Init();")
189 190 191 192 193 194
      end
      output.puts("}\n")

      output.puts("static void CMock_Verify(void)")
      output.puts("{")
      mocks.each do |mock|
195 196
        mock_clean = mock.gsub(/(?:-|\s+)/, "_")
        output.puts("  #{mock_clean}_Verify();")
197 198 199 200 201 202
      end
      output.puts("}\n")

      output.puts("static void CMock_Destroy(void)")
      output.puts("{")
      mocks.each do |mock|
203 204
        mock_clean = mock.gsub(/(?:-|\s+)/, "_")
        output.puts("  #{mock_clean}_Destroy();")
205 206 207 208 209
      end
      output.puts("}\n")
    end
  end
  
210 211
  def create_suite_setup_and_teardown(output)
    unless (@options[:suite_setup].nil?)
212
      output.puts("\n//=======Suite Setup=====")
213 214 215 216 217 218
      output.puts("static int suite_setup(void)")
      output.puts("{")
      output.puts(@options[:suite_setup])
      output.puts("}")
    end
    unless (@options[:suite_teardown].nil?)
219
      output.puts("\n//=======Suite Teardown=====")
220 221 222 223 224 225
      output.puts("static int suite_teardown(int num_failures)")
      output.puts("{")
      output.puts(@options[:suite_teardown])
      output.puts("}")
    end
  end
226 227
  
  def create_runtest(output, used_mocks)
228
    cexception = @options[:plugins].include? :cexception
229 230 231
    va_args1   = @options[:use_param_tests] ? ', ...' : ''
    va_args2   = @options[:use_param_tests] ? '__VA_ARGS__' : ''
    output.puts("\n//=======Test Runner Used To Run Each Test Below=====")
232
    output.puts("#define RUN_TEST_NO_ARGS") if @options[:use_param_tests] 
233 234
    output.puts("#define RUN_TEST(TestFunc, TestLineNum#{va_args1}) \\")
    output.puts("{ \\")
M
mvandervoord 已提交
235
    output.puts("  Unity.CurrentTestName = #TestFunc#{va_args2.empty? ? '' : " \"(\" ##{va_args2} \")\""}; \\")
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
    output.puts("  Unity.CurrentTestLineNumber = TestLineNum; \\")
    output.puts("  Unity.NumberOfTests++; \\")
    output.puts("  if (TEST_PROTECT()) \\")
    output.puts("  { \\")
    output.puts("    CEXCEPTION_T e; \\") if cexception
    output.puts("    Try { \\") if cexception
    output.puts("      CMock_Init(); \\") unless (used_mocks.empty?) 
    output.puts("      setUp(); \\")
    output.puts("      TestFunc(#{va_args2}); \\")
    output.puts("      CMock_Verify(); \\") unless (used_mocks.empty?)
    output.puts("    } Catch(e) { TEST_ASSERT_EQUAL_HEX32_MESSAGE(CEXCEPTION_NONE, e, \"Unhandled Exception!\"); } \\") if cexception
    output.puts("  } \\")
    output.puts("  CMock_Destroy(); \\") unless (used_mocks.empty?)
    output.puts("  if (TEST_PROTECT() && !TEST_IS_IGNORED) \\")
    output.puts("  { \\")
    output.puts("    tearDown(); \\")
    output.puts("  } \\")
    output.puts("  UnityConcludeTest(); \\")
    output.puts("}\n")
255 256
  end
  
257
  def create_reset(output, used_mocks)
258
    output.puts("\n//=======Test Reset Option=====")
259 260 261 262 263 264 265 266 267
    output.puts("void resetTest()")
    output.puts("{")
    output.puts("  CMock_Verify();") unless (used_mocks.empty?)
    output.puts("  CMock_Destroy();") unless (used_mocks.empty?)
    output.puts("  tearDown();")
    output.puts("  CMock_Init();") unless (used_mocks.empty?) 
    output.puts("  setUp();")
    output.puts("}")
  end
268
  
269
  def create_main(output, filename, tests)
270
    output.puts("\n\n//=======MAIN=====")
271
    output.puts("int main(void)")
272
    output.puts("{")
273
    output.puts("  suite_setup();") unless @options[:suite_setup].nil?
274
    output.puts("  Unity.TestFile = \"#{filename}\";")
275
    output.puts("  UnityBegin();")
276 277 278
    if (@options[:use_param_tests])
      tests.each do |test|
        if ((test[:args].nil?) or (test[:args].empty?))
279
          output.puts("  RUN_TEST(#{test[:test]}, #{test[:line_number]}, RUN_TEST_NO_ARGS);")
280
        else
281
          test[:args].each {|args| output.puts("  RUN_TEST(#{test[:test]}, #{test[:line_number]}, #{args});")}
282
        end
283
      end
284
    else
285
        tests.each { |test| output.puts("  RUN_TEST(#{test[:test]}, #{test[:line_number]});") }
286 287
    end
    output.puts()
288
    output.puts("  return #{@options[:suite_teardown].nil? ? "" : "suite_teardown"}(UnityEnd());")
289 290 291 292 293 294
    output.puts("}")
  end
end


if ($0 == __FILE__)
295 296
  options = { :includes => [] }
  yaml_file = nil
297
  
298 299
  #parse out all the options first
  ARGV.reject! do |arg| 
300
    case(arg)
M
mvandervoord 已提交
301 302
      when '-cexception' 
        options[:plugins] = [:cexception]; true
M
mvandervoord 已提交
303
      when /\.*\.yml/
M
mvandervoord 已提交
304
        options = UnityTestRunnerGenerator.grab_config(arg); true
305
      else false
306 307 308 309
    end
  end     
           
  #make sure there is at least one parameter left (the input file)
310
  if !ARGV[0]
311
    puts ["usage: ruby #{__FILE__} (yaml) (options) input_test_file output_test_runner (includes)",
312
           "  blah.yml    - will use config options in the yml file (see docs)",
313
           "  -cexception - include cexception support"].join("\n")
314 315 316
    exit 1
  end
  
317
  #create the default test runner name if not specified
318
  ARGV[1] = ARGV[0].gsub(".c","_Runner.c") if (!ARGV[1])
319
  
320
  #everything else is an include file
M
mvandervoord 已提交
321
  options[:includes] ||= (ARGV.slice(2..-1).flatten.compact) if (ARGV.size > 2)
M
mvandervoord 已提交
322
  
323
  UnityTestRunnerGenerator.new(options).run(ARGV[0], ARGV[1])
324
end