generate_test_runner.rb 11.0 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 34 35 36
    tests = []
    includes = []
    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
      tests      = find_tests(input)
      includes   = find_includes(input)
44 45 46
      used_mocks = find_mocks(includes)
    end

47
    #build runner file
48
    File.open(output_file, 'w') do |output|
49
      create_header(output, used_mocks)
50 51
      create_externs(output, tests, used_mocks)
      create_mock_management(output, used_mocks)
52
      create_suite_setup_and_teardown(output)
53
      create_reset(output, used_mocks)
54
      create_main(output, input_file, tests)
55 56 57 58
    end
    
    all_files_used = [input_file, output_file]
    all_files_used += includes.map {|filename| filename + '.c'} unless includes.empty?
59
    all_files_used += @options[:includes] unless @options[:includes].empty?
60 61 62 63
    return all_files_used.uniq
  end
  
  def find_tests(input_file)
64
    tests_raw = []
65
    tests_args = []
66 67
    tests_and_line_numbers = []
    
68
    input_file.rewind
69
    source_raw = input_file.read
70 71 72 73
    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
74 75

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

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

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

      output.puts("static void CMock_Verify(void)")
      output.puts("{")
      mocks.each do |mock|
176
        output.puts("  #{mock}_Verify();")
177 178 179 180 181 182
      end
      output.puts("}\n")

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


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