generate_test_runner.rb 8.9 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)
M
mvandervoord 已提交
12
    @options = { :includes => [], :framework => :unity }
13 14 15 16 17 18 19 20
    case(options)
      when NilClass then @options
      when String   then @options = UnityTestRunnerGenerator.grab_config(options)
      when Hash     then @options = options
      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)
M
mvandervoord 已提交
22
    options = { :includes => [], :framework => :unity }
23 24
    unless (config_file.nil? or config_file.empty?)
      require 'yaml'
25 26
      yaml_guts = YAML.load_file(config_file)
      yaml_goodness = yaml_guts[:unity] ? yaml_guts[:unity] : yaml_guts[:cmock]
27 28
      options[:cexception] = 1 unless (yaml_goodness[:plugins] & ['cexception', :cexception]).empty?
      options[:order]      = 1 if     (yaml_goodness[:enforce_strict_ordering])
M
mvandervoord 已提交
29
      options[:framework]  =          (yaml_goodness[:framework] || :unity)
30
      options[:includes]   <<         (yaml_goodness[:includes])
31
    end
32
    return(options)
33 34
  end

35
  def run(input_file, output_file, options=nil)
36 37 38 39
    tests = []
    includes = []
    used_mocks = []
    
40
    @options = options unless options.nil?
41 42
    module_name = File.basename(input_file)
    
43
    #pull required data from source file
44
    File.open(input_file, 'r') do |input|
45 46
      tests      = find_tests(input)
      includes   = find_includes(input)
47 48
      used_mocks = find_mocks(includes)
    end
49
    
50
    puts "Creating test runner for #{module_name}..."
51

52
    #build runner file
53
    File.open(output_file, 'w') do |output|
54
      create_header(output, used_mocks)
55 56 57
      create_externs(output, tests, used_mocks)
      create_mock_management(output, used_mocks)
      create_runtest(output, used_mocks)
58
	    create_reset(output, used_mocks)
59
      create_main(output, input_file, tests)
60 61 62 63
    end
    
    all_files_used = [input_file, output_file]
    all_files_used += includes.map {|filename| filename + '.c'} unless includes.empty?
64
    all_files_used += @options[:includes] unless @options[:includes].empty?
65 66 67 68
    return all_files_used.uniq
  end
  
  def find_tests(input_file)
69 70 71
    tests_raw = []
    tests_and_line_numbers = []
    
72
    input_file.rewind
73 74 75 76
    source_raw = input_file.read
    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
77
                              | (;|\{|\}) /x) # Match ;, {, and } as end of lines
78 79

    lines.each_with_index do |line, index|
80
      if line =~ /^\s*void\s+test(.*?)\s*\(\s*void\s*\)/
81 82 83 84 85 86 87 88 89 90 91 92 93 94
        tests_raw << ("test" + $1)
      end
    end

    source_lines = source_raw.split("\n")
    source_index = 0;

    tests_raw.each do |test|
      source_lines[source_index..-1].each_with_index do |line, index|
        if (line =~ /#{test}/)
          source_index += index
          tests_and_line_numbers << {:name => test, :line_number => (source_index+1)}
          break
        end
95 96
      end
    end
97
    return tests_and_line_numbers
98 99 100 101 102 103
  end

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

      output.puts("static void CMock_Verify(void)")
      output.puts("{")
      mocks.each do |mock|
170
        output.puts("  #{mock}_Verify();")
171 172 173 174 175 176
      end
      output.puts("}\n")

      output.puts("static void CMock_Destroy(void)")
      output.puts("{")
      mocks.each do |mock|
177
        output.puts("  #{mock}_Destroy();")
178 179 180 181 182 183 184 185 186
      end
      output.puts("}\n")
    end
  end
  
  
  def create_runtest(output, used_mocks)
    output.puts("static void runTest(UnityTestFunction test)")
    output.puts("{")
187 188
    output.puts("  if (TEST_PROTECT())")
    output.puts("  {")
189
    output.puts("    CEXCEPTION_T e;") if @options[:cexception]
190 191 192 193 194
    output.puts("    Try {") if @options[:cexception]
    output.puts("      CMock_Init();") unless (used_mocks.empty?) 
    output.puts("      setUp();")
    output.puts("      test();")
    output.puts("      CMock_Verify();") unless (used_mocks.empty?)
195
    output.puts("    } Catch(e) { TEST_ASSERT_EQUAL_HEX32_MESSAGE(CEXCEPTION_NONE, e, \"Unhandled Exception!\"); }") if @options[:cexception]
196 197
    output.puts("  }")
    output.puts("  CMock_Destroy();") unless (used_mocks.empty?)
198
    output.puts("  if (TEST_PROTECT() && !TEST_IS_IGNORED)")
199 200 201
    output.puts("  {")
    output.puts("    tearDown();")
    output.puts("  }")
202 203 204
    output.puts("}")
  end
  
205 206 207 208 209 210 211 212 213 214
  def create_reset(output, used_mocks)
    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
215
  
216
  def create_main(output, filename, tests)
217 218
    output.puts()
    output.puts()
219
    output.puts("int main(void)")
220
    output.puts("{")
221
    output.puts("  Unity.TestFile = \"#{filename}\";")
222
    output.puts("  UnityBegin();")
223 224
    output.puts()

225
    output.puts("  // RUN_TEST calls runTest")  	
226
    tests.each do |test|
227
      output.puts("  RUN_TEST(#{test[:name]}, #{test[:line_number]});")
228 229 230
    end

    output.puts()
231
    output.puts("  return UnityEnd();")
232 233 234 235 236 237
    output.puts("}")
  end
end


if ($0 == __FILE__)
238 239
  usage = ["usage: ruby #{__FILE__} (yaml) (options) input_test_file output_test_runner (includes)",
           "  blah.yml    - will use config options in the yml file (see CMock docs)",
240
           "  -cexception - include cexception support",
241
           "  -order      - include cmock order-enforcement support" ]
242

243 244
  options = { :includes => [] }
  yaml_file = nil
245
  
246 247 248 249 250 251
  #parse out all the options first
  ARGV.reject! do |arg| 
    if (arg =~ /\-(\w+)/) 
      options[$1.to_sym] = 1
      true
    elsif (arg =~ /(\w+\.yml)/)
252
      options = UnityTestRunnerGenerator.grab_config(arg)
253 254 255 256 257 258 259
      true
    else
      false
    end
  end     
           
  #make sure there is at least one parameter left (the input file)
260 261 262 263 264
  if !ARGV[0]
    puts usage
    exit 1
  end
  
265
  #create the default test runner name if not specified
266
  ARGV[1] = ARGV[0].gsub(".c","_Runner.c") if (!ARGV[1])
267
  
268
  #everything else is an include file
269
  options[:includes] = (ARGV.slice(2..-1).flatten.compact) if (ARGV.size > 2)
M
mvandervoord 已提交
270
  
271
  UnityTestRunnerGenerator.new(options).run(ARGV[0], ARGV[1])
272
end