generate_test_runner.rb 11.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
48
    generate(input_file, output_file, tests, used_mocks)
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
  
57
  def generate(input_file, output_file, tests, used_mocks)
58
    File.open(output_file, 'w') do |output|
59
      create_header(output, used_mocks)
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 114 115
  end

  def find_includes(input_file)
    input_file.rewind
    includes = []
    input_file.readlines.each do |line|
116
      scan_results = line.scan(/^\s*#include\s+\"\s*(.+)\.[hH]\s*\"/)
117 118 119 120 121 122 123 124
      includes << scan_results[0][0] if (scan_results.size > 0)
    end
    return includes
  end
  
  def find_mocks(includes)
    mock_headers = []
    includes.each do |include_file|
M
mvandervoord 已提交
125
      mock_headers << File.basename(include_file) if (include_file =~ /^mock/i)
126 127 128 129
    end
    return mock_headers  
  end
  
130
  def create_header(output, mocks)
131
    output.puts('/* AUTOGENERATED FILE. DO NOT EDIT. */')
132 133
    create_runtest(output, mocks)
    output.puts("\n//=======Automagically Detected Files To Include=====")
M
mvandervoord 已提交
134
    output.puts("#include \"#{@options[:framework].to_s}.h\"")
135
    output.puts('#include "cmock.h"') unless (mocks.empty?)
136
    @options[:includes].flatten.uniq.compact.each do |inc|
M
mvandervoord 已提交
137
      output.puts("#include #{inc.include?('<') ? inc : "\"#{inc.gsub('.h','')}.h\""}")
138 139 140
    end
    output.puts('#include <setjmp.h>')
    output.puts('#include <stdio.h>')
141
    output.puts('#include "CException.h"') if @options[:plugins].include?(:cexception)
142 143 144
    mocks.each do |mock|
      output.puts("#include \"#{mock.gsub('.h','')}.h\"")
    end
145
    if @options[:enforce_strict_ordering]
146
      output.puts('')    
147 148 149 150
      output.puts('int GlobalExpectCount;') 
      output.puts('int GlobalVerifyOrder;') 
      output.puts('char* GlobalOrderError;') 
    end
151 152 153
  end
  
  def create_externs(output, tests, mocks)
154
    output.puts("\n//=======External Functions This Runner Calls=====")
155 156 157
    output.puts("extern void setUp(void);")
    output.puts("extern void tearDown(void);")
    tests.each do |test|
158
      output.puts("extern void #{test[:test]}(#{test[:call] || 'void'});")
159 160 161 162 163 164
    end
    output.puts('')
  end
  
  def create_mock_management(output, mocks)
    unless (mocks.empty?)
165
      output.puts("\n//=======Mock Management=====")
166 167
      output.puts("static void CMock_Init(void)")
      output.puts("{")
168
      if @options[:enforce_strict_ordering]
169 170 171
        output.puts("  GlobalExpectCount = 0;")
        output.puts("  GlobalVerifyOrder = 0;") 
        output.puts("  GlobalOrderError = NULL;") 
172
      end
173
      mocks.each do |mock|
174
        output.puts("  #{mock}_Init();")
175 176 177 178 179 180
      end
      output.puts("}\n")

      output.puts("static void CMock_Verify(void)")
      output.puts("{")
      mocks.each do |mock|
181
        output.puts("  #{mock}_Verify();")
182 183 184 185 186 187
      end
      output.puts("}\n")

      output.puts("static void CMock_Destroy(void)")
      output.puts("{")
      mocks.each do |mock|
188
        output.puts("  #{mock}_Destroy();")
189 190 191 192 193
      end
      output.puts("}\n")
    end
  end
  
194 195
  def create_suite_setup_and_teardown(output)
    unless (@options[:suite_setup].nil?)
196
      output.puts("\n//=======Suite Setup=====")
197 198 199 200 201 202
      output.puts("static int suite_setup(void)")
      output.puts("{")
      output.puts(@options[:suite_setup])
      output.puts("}")
    end
    unless (@options[:suite_teardown].nil?)
203
      output.puts("\n//=======Suite Teardown=====")
204 205 206 207 208 209
      output.puts("static int suite_teardown(int num_failures)")
      output.puts("{")
      output.puts(@options[:suite_teardown])
      output.puts("}")
    end
  end
210 211
  
  def create_runtest(output, used_mocks)
212
    cexception = @options[:plugins].include? :cexception
213 214 215
    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=====")
216
    output.puts("#define RUN_TEST_NO_ARGS") if @options[:use_param_tests] 
217 218
    output.puts("#define RUN_TEST(TestFunc, TestLineNum#{va_args1}) \\")
    output.puts("{ \\")
M
mvandervoord 已提交
219
    output.puts("  Unity.CurrentTestName = #TestFunc#{va_args2.empty? ? '' : " \"(\" ##{va_args2} \")\""}; \\")
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
    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")
239 240
  end
  
241
  def create_reset(output, used_mocks)
242
    output.puts("\n//=======Test Reset Option=====")
243 244 245 246 247 248 249 250 251
    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
252
  
253
  def create_main(output, filename, tests)
254
    output.puts("\n\n//=======MAIN=====")
255
    output.puts("int main(void)")
256
    output.puts("{")
257
    output.puts("  suite_setup();") unless @options[:suite_setup].nil?
258
    output.puts("  Unity.TestFile = \"#{filename}\";")
259
    output.puts("  UnityBegin();")
260 261 262
    if (@options[:use_param_tests])
      tests.each do |test|
        if ((test[:args].nil?) or (test[:args].empty?))
263
          output.puts("  RUN_TEST(#{test[:test]}, #{test[:line_number]}, RUN_TEST_NO_ARGS);")
264
        else
265
          test[:args].each {|args| output.puts("  RUN_TEST(#{test[:test]}, #{test[:line_number]}, #{args});")}
266
        end
267
      end
268
    else
269
        tests.each { |test| output.puts("  RUN_TEST(#{test[:test]}, #{test[:line_number]});") }
270 271
    end
    output.puts()
272
    output.puts("  return #{@options[:suite_teardown].nil? ? "" : "suite_teardown"}(UnityEnd());")
273 274 275 276 277 278
    output.puts("}")
  end
end


if ($0 == __FILE__)
279 280
  options = { :includes => [] }
  yaml_file = nil
281
  
282 283
  #parse out all the options first
  ARGV.reject! do |arg| 
284
    case(arg)
M
mvandervoord 已提交
285 286
      when '-cexception' 
        options[:plugins] = [:cexception]; true
M
mvandervoord 已提交
287
      when /\.*\.yml/
M
mvandervoord 已提交
288
        options = UnityTestRunnerGenerator.grab_config(arg); true
289
      else false
290 291 292 293
    end
  end     
           
  #make sure there is at least one parameter left (the input file)
294
  if !ARGV[0]
295
    puts ["usage: ruby #{__FILE__} (yaml) (options) input_test_file output_test_runner (includes)",
296
           "  blah.yml    - will use config options in the yml file (see docs)",
297
           "  -cexception - include cexception support"].join("\n")
298 299 300
    exit 1
  end
  
301
  #create the default test runner name if not specified
302
  ARGV[1] = ARGV[0].gsub(".c","_Runner.c") if (!ARGV[1])
303
  
304
  #everything else is an include file
M
mvandervoord 已提交
305
  options[:includes] ||= (ARGV.slice(2..-1).flatten.compact) if (ARGV.size > 2)
M
mvandervoord 已提交
306
  
307
  UnityTestRunnerGenerator.new(options).run(ARGV[0], ARGV[1])
308
end