generate_test_runner.rb 13.7 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
      else          raise "If you specify arguments, it should be a filename or a hash of options"
    end
20
    require "#{File.expand_path(File.dirname(__FILE__))}/type_sanitizer"
21
  end
22

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

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

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

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

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

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

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

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

  def find_tests(source)
83
    tests_raw = []
84
    tests_args = []
85
    tests_and_line_numbers = []
86 87

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

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

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

121
    return tests_and_line_numbers
122 123
  end

124 125
  def find_includes(source)

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

131
    #parse out includes
132 133 134 135
    includes = {
      local: source.scan(/^\s*#include\s+\"\s*(.+)\.[hH]\s*\"/).flatten,
      system: source.scan(/^\s*#include\s+<\s*(.+)\s*>/).flatten.map { |inc| "<#{inc}>" }
    }
136
    return includes
137
  end
138

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

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

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

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

      output.puts("static void CMock_Verify(void)")
      output.puts("{")
      mocks.each do |mock|
204
        mock_clean = TypeSanitizer.sanitize_c_identifier(mock)
205
        output.puts("  #{mock_clean}_Verify();")
206 207 208 209 210 211
      end
      output.puts("}\n")

      output.puts("static void CMock_Destroy(void)")
      output.puts("{")
      mocks.each do |mock|
212
        mock_clean = TypeSanitizer.sanitize_c_identifier(mock)
213
        output.puts("  #{mock_clean}_Destroy();")
214 215 216 217
      end
      output.puts("}\n")
    end
  end
218

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

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

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

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


if ($0 == __FILE__)
305 306
  options = { :includes => [] }
  yaml_file = nil
307

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

323
  #make sure there is at least one parameter left (the input file)
324
  if !ARGV[0]
325 326 327 328 329 330 331
    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",
332
           "  options:",
333 334 335 336 337 338 339
           "    -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)",
340
          ].join("\n")
341 342
    exit 1
  end
343

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


348
  UnityTestRunnerGenerator.new(options).run(ARGV[0], ARGV[1])
349
end