generate_test_runner.rb 13.5 KB
Newer Older
1 2 3 4
# ==========================================
#   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]
5
# ==========================================
6

7
$QUICK_RUBY_VERSION = RUBY_VERSION.split('.').inject(0){|vv,v| vv * 100 + v.to_i }
8
File.expand_path(File.join(File.dirname(__FILE__),'colour_prompt'))
9 10 11

class UnityTestRunnerGenerator

12
  def initialize(options = nil)
13
    @options = UnityTestRunnerGenerator.default_options
14 15
    case(options)
      when NilClass then @options
16 17
      when String   then @options.merge!(UnityTestRunnerGenerator.grab_config(options))
      when Hash     then @options.merge!(options)
18 19 20
      else          raise "If you specify arguments, it should be a filename or a hash of options"
    end
  end
21

22
  def self.default_options
23 24 25 26 27 28 29 30 31 32
    {
      :includes      => [],
      :plugins       => [],
      :framework     => :unity,
      :test_prefix   => "test|spec|should",
      :setup_name    => "setUp",
      :teardown_name => "tearDown",
    }
  end

M
mkarlesky 已提交
33
  def self.grab_config(config_file)
34
    options = self.default_options
35 36
    unless (config_file.nil? or config_file.empty?)
      require 'yaml'
37
      yaml_guts = YAML.load_file(config_file)
38
      options.merge!(yaml_guts[:unity] || yaml_guts[:cmock])
39
      raise "No :unity or :cmock section found in #{config_file}" unless options
40
    end
41
    return(options)
42 43
  end

44
  def run(input_file, output_file, options=nil)
45
    tests = []
46
    testfile_includes = []
47
    used_mocks = []
48

49
    @options.merge!(options) unless options.nil?
50
    module_name = File.basename(input_file)
51

52
    #pull required data from source file
53
    source = File.read(input_file)
54
    source = source.force_encoding("ISO-8859-1").encode("utf-8", :replace => nil) if ($QUICK_RUBY_VERSION > 10900)
55 56 57
    tests               = find_tests(source)
    testfile_includes   = find_includes(source)
    used_mocks          = find_mocks(testfile_includes)
58

59
    #build runner file
S
shellyniz 已提交
60
    generate(input_file, output_file, tests, used_mocks, testfile_includes)
61

62 63
    #determine which files were used to return them
    all_files_used = [input_file, output_file]
64
    all_files_used += testfile_includes.map {|filename| filename + '.c'} unless testfile_includes.empty?
65 66 67
    all_files_used += @options[:includes] unless @options[:includes].empty?
    return all_files_used.uniq
  end
68

S
shellyniz 已提交
69
  def generate(input_file, output_file, tests, used_mocks, testfile_includes)
70
    File.open(output_file, 'w') do |output|
S
shellyniz 已提交
71
      create_header(output, used_mocks, testfile_includes)
72 73
      create_externs(output, tests, used_mocks)
      create_mock_management(output, used_mocks)
74
      create_suite_setup_and_teardown(output)
75
      create_reset(output, used_mocks)
76
      create_main(output, input_file, tests, used_mocks)
77 78
    end
  end
79 80

  def find_tests(source)
81
    tests_raw = []
82
    tests_args = []
83
    tests_and_line_numbers = []
84 85

    source_scrubbed = source.gsub(/\/\/.*$/, '')               # remove line comments
86 87 88
    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
89 90

    lines.each_with_index do |line, index|
91
      #find tests
92
      if line =~ /^((?:\s*TEST_CASE\s*\(.*?\)\s*)*)\s*void\s+((?:#{@options[:test_prefix]}).*)\s*\(\s*(.*)\s*\)/
93
        arguments = $1
94 95
        name = $2
        call = $3
96 97 98 99 100
        args = nil
        if (@options[:use_param_tests] and !arguments.empty?)
          args = []
          arguments.scan(/\s*TEST_CASE\s*\((.*)\)\s*$/) {|a| args << a[0]}
        end
101
        tests_and_line_numbers << { :test => name, :args => args, :call => call, :line_number => 0 }
102
        tests_args = []
103 104 105
      end
    end

106
    #determine line numbers and create tests to run
107
    source_lines = source.split("\n")
108
    source_index = 0;
109
    tests_and_line_numbers.size.times do |i|
110
      source_lines[source_index..-1].each_with_index do |line, index|
111
        if (line =~ /#{tests_and_line_numbers[i][:test]}/)
112
          source_index += index
113
          tests_and_line_numbers[i][:line_number] = source_index + 1
114 115
          break
        end
116 117
      end
    end
118

119
    return tests_and_line_numbers
120 121
  end

122 123
  def find_includes(source)

124 125
    #remove comments (block and line, in three steps to ensure correct precedence)
    source.gsub!(/\/\/(?:.+\/\*|\*(?:$|[^\/])).*$/, '')  # remove line comments that comment out the start of blocks
126
    source.gsub!(/\/\*.*?\*\//m, '')                     # remove block comments
127
    source.gsub!(/\/\/.*$/, '')                          # remove line comments (all that remain)
128

129
    #parse out includes
130 131 132 133
    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
134
  end
135

136 137 138
  def find_mocks(includes)
    mock_headers = []
    includes.each do |include_file|
M
mvandervoord 已提交
139
      mock_headers << File.basename(include_file) if (include_file =~ /^mock/i)
140
    end
141
    return mock_headers
142
  end
143

144
  def create_header(output, mocks, testfile_includes=[])
145
    output.puts('/* AUTOGENERATED FILE. DO NOT EDIT. */')
146 147
    create_runtest(output, mocks)
    output.puts("\n//=======Automagically Detected Files To Include=====")
M
mvandervoord 已提交
148
    output.puts("#include \"#{@options[:framework].to_s}.h\"")
149
    output.puts('#include "cmock.h"') unless (mocks.empty?)
150
    @options[:includes].flatten.uniq.compact.each do |inc|
M
mvandervoord 已提交
151
      output.puts("#include #{inc.include?('<') ? inc : "\"#{inc.gsub('.h','')}.h\""}")
152 153 154
    end
    output.puts('#include <setjmp.h>')
    output.puts('#include <stdio.h>')
155
    output.puts('#include "CException.h"') if @options[:plugins].include?(:cexception)
156 157 158
    testfile_includes.delete_if{|inc| inc =~ /(unity|cmock)/}
    testrunner_includes = testfile_includes - mocks
    testrunner_includes.each do |inc|
159 160
    output.puts("#include #{inc.include?('<') ? inc : "\"#{inc.gsub('.h','')}.h\""}")
  end
161 162 163
    mocks.each do |mock|
      output.puts("#include \"#{mock.gsub('.h','')}.h\"")
    end
164
    if @options[:enforce_strict_ordering]
165 166 167 168
      output.puts('')
      output.puts('int GlobalExpectCount;')
      output.puts('int GlobalVerifyOrder;')
      output.puts('char* GlobalOrderError;')
169
    end
170
  end
171

172
  def create_externs(output, tests, mocks)
173
    output.puts("\n//=======External Functions This Runner Calls=====")
174 175
    output.puts("extern void #{@options[:setup_name]}(void);")
    output.puts("extern void #{@options[:teardown_name]}(void);")
176
    tests.each do |test|
177
      output.puts("extern void #{test[:test]}(#{test[:call] || 'void'});")
178 179 180
    end
    output.puts('')
  end
181

182 183
  def create_mock_management(output, mocks)
    unless (mocks.empty?)
184
      output.puts("\n//=======Mock Management=====")
185 186
      output.puts("static void CMock_Init(void)")
      output.puts("{")
187
      if @options[:enforce_strict_ordering]
188
        output.puts("  GlobalExpectCount = 0;")
189 190
        output.puts("  GlobalVerifyOrder = 0;")
        output.puts("  GlobalOrderError = NULL;")
191
      end
192
      mocks.each do |mock|
193 194
        mock_clean = mock.gsub(/(?:-|\s+)/, "_")
        output.puts("  #{mock_clean}_Init();")
195 196 197 198 199 200
      end
      output.puts("}\n")

      output.puts("static void CMock_Verify(void)")
      output.puts("{")
      mocks.each do |mock|
201 202
        mock_clean = mock.gsub(/(?:-|\s+)/, "_")
        output.puts("  #{mock_clean}_Verify();")
203 204 205 206 207 208
      end
      output.puts("}\n")

      output.puts("static void CMock_Destroy(void)")
      output.puts("{")
      mocks.each do |mock|
209 210
        mock_clean = mock.gsub(/(?:-|\s+)/, "_")
        output.puts("  #{mock_clean}_Destroy();")
211 212 213 214
      end
      output.puts("}\n")
    end
  end
215

216 217
  def create_suite_setup_and_teardown(output)
    unless (@options[:suite_setup].nil?)
218
      output.puts("\n//=======Suite Setup=====")
219 220 221 222 223 224
      output.puts("static int suite_setup(void)")
      output.puts("{")
      output.puts(@options[:suite_setup])
      output.puts("}")
    end
    unless (@options[:suite_teardown].nil?)
225
      output.puts("\n//=======Suite Teardown=====")
226 227 228 229 230 231
      output.puts("static int suite_teardown(int num_failures)")
      output.puts("{")
      output.puts(@options[:suite_teardown])
      output.puts("}")
    end
  end
232

233
  def create_runtest(output, used_mocks)
234
    cexception = @options[:plugins].include? :cexception
235 236 237
    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=====")
238
    output.puts("#define RUN_TEST_NO_ARGS") if @options[:use_param_tests]
239 240
    output.puts("#define RUN_TEST(TestFunc, TestLineNum#{va_args1}) \\")
    output.puts("{ \\")
M
mvandervoord 已提交
241
    output.puts("  Unity.CurrentTestName = #TestFunc#{va_args2.empty? ? '' : " \"(\" ##{va_args2} \")\""}; \\")
242 243
    output.puts("  Unity.CurrentTestLineNumber = TestLineNum; \\")
    output.puts("  Unity.NumberOfTests++; \\")
244
    output.puts("  CMock_Init(); \\") unless (used_mocks.empty?)
245 246 247 248
    output.puts("  if (TEST_PROTECT()) \\")
    output.puts("  { \\")
    output.puts("    CEXCEPTION_T e; \\") if cexception
    output.puts("    Try { \\") if cexception
249
    output.puts("      #{@options[:setup_name]}(); \\")
250 251 252 253 254
    output.puts("      TestFunc(#{va_args2}); \\")
    output.puts("    } Catch(e) { TEST_ASSERT_EQUAL_HEX32_MESSAGE(CEXCEPTION_NONE, e, \"Unhandled Exception!\"); } \\") if cexception
    output.puts("  } \\")
    output.puts("  if (TEST_PROTECT() && !TEST_IS_IGNORED) \\")
    output.puts("  { \\")
255
    output.puts("    #{@options[:teardown_name]}(); \\")
256
    output.puts("    CMock_Verify(); \\") unless (used_mocks.empty?)
257
    output.puts("  } \\")
258
    output.puts("  CMock_Destroy(); \\") unless (used_mocks.empty?)
259 260
    output.puts("  UnityConcludeTest(); \\")
    output.puts("}\n")
261
  end
262

263
  def create_reset(output, used_mocks)
264
    output.puts("\n//=======Test Reset Option=====")
265 266
    output.puts("void resetTest(void);")
    output.puts("void resetTest(void)")
267 268 269
    output.puts("{")
    output.puts("  CMock_Verify();") unless (used_mocks.empty?)
    output.puts("  CMock_Destroy();") unless (used_mocks.empty?)
270
    output.puts("  #{@options[:teardown_name]}();")
271
    output.puts("  CMock_Init();") unless (used_mocks.empty?)
272
    output.puts("  #{@options[:setup_name]}();")
273 274
    output.puts("}")
  end
275

276
  def create_main(output, filename, tests, used_mocks)
277
    output.puts("\n\n//=======MAIN=====")
278
    output.puts("int main(void)")
279
    output.puts("{")
280
    output.puts("  suite_setup();") unless @options[:suite_setup].nil?
M
Mark VanderVoord 已提交
281
    output.puts("  UnityBegin(\"#{filename}\");")
282 283 284
    if (@options[:use_param_tests])
      tests.each do |test|
        if ((test[:args].nil?) or (test[:args].empty?))
285
          output.puts("  RUN_TEST(#{test[:test]}, #{test[:line_number]}, RUN_TEST_NO_ARGS);")
286
        else
287
          test[:args].each {|args| output.puts("  RUN_TEST(#{test[:test]}, #{test[:line_number]}, #{args});")}
288
        end
289
      end
290
    else
291
        tests.each { |test| output.puts("  RUN_TEST(#{test[:test]}, #{test[:line_number]});") }
292 293
    end
    output.puts()
294
    output.puts("  CMock_Guts_MemFreeFinal();") unless used_mocks.empty?
295
    output.puts("  return #{@options[:suite_teardown].nil? ? "" : "suite_teardown"}(UnityEnd());")
296 297 298 299 300 301
    output.puts("}")
  end
end


if ($0 == __FILE__)
302 303
  options = { :includes => [] }
  yaml_file = nil
304

305
  #parse out all the options first (these will all be removed as we go)
306
  ARGV.reject! do |arg|
307
    case(arg)
308
      when '-cexception'
M
mvandervoord 已提交
309
        options[:plugins] = [:cexception]; true
310
      when /\.*\.ya?ml/
M
mvandervoord 已提交
311
        options = UnityTestRunnerGenerator.grab_config(arg); true
312 313
      when /\.*\.h/
        options[:includes] << arg; true
314 315
      when /--(\w+)=\"?(.*)\"?/
        options[$1.to_sym] = $2; true
316
      else false
317
    end
318 319
  end

320
  #make sure there is at least one parameter left (the input file)
321
  if !ARGV[0]
322 323 324 325 326 327 328
    puts ["\nusage: ruby #{__FILE__} (files) (options) input_test_file (output)",
           "\n  input_test_file         - this is the C file you want to create a runner for",
           "  output                  - this is the name of the runner file to generate",
           "                            defaults to (input_test_file)_Runner",
           "  files:",
           "    *.yml / *.yaml        - loads configuration from here in :unity or :cmock",
           "    *.h                   - header files are added as #includes in runner",
329
           "  options:",
330 331 332 333 334 335 336
           "    -cexception           - include cexception support",
           "    --setup_name=\"\"       - redefine setUp func name to something else",
           "    --teardown_name=\"\"    - redefine tearDown func name to something else",
           "    --test_prefix=\"\"      - redefine test prefix from default test|spec|should",
           "    --suite_setup=\"\"      - code to execute for setup of entire suite",
           "    --suite_teardown=\"\"   - code to execute for teardown of entire suite",
           "    --use_param_tests=1   - enable parameterized tests (disabled by default)",
337
          ].join("\n")
338 339
    exit 1
  end
340

341
  #create the default test runner name if not specified
342
  ARGV[1] = ARGV[0].gsub(".c","_Runner.c") if (!ARGV[1])
343 344


345
  UnityTestRunnerGenerator.new(options).run(ARGV[0], ARGV[1])
346
end