generate_test_runner.rb 9.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 12 13 14 15 16 17 18 19 20
  def initialize(options = nil)
    @options = { :includes => [] }
    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)
22
    options = { :includes => [] }
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 29 30
      options[:cexception] = 1 unless (yaml_goodness[:plugins] & ['cexception', :cexception]).empty?
      options[:coverage  ] = 1 if     (yaml_goodness[:coverage])
      options[:order]      = 1 if     (yaml_goodness[:enforce_strict_ordering])
      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 104 105 106 107 108 109 110 111 112
  end

  def find_includes(input_file)
    input_file.rewind
    includes = []
    input_file.readlines.each do |line|
      scan_results = line.scan(/^#include\s+\"\s*(.+)\.h\s*\"/)
      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 120
    output.puts('/* AUTOGENERATED FILE. DO NOT EDIT. */')
    output.puts('#include "unity.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
    output.puts('#include "BullseyeCoverage.h"') if @options[:coverage]
129 130 131
    mocks.each do |mock|
      output.puts("#include \"#{mock.gsub('.h','')}.h\"")
    end
132 133
    output.puts('')    
    output.puts('char MessageBuffer[50];')
134 135 136 137 138
    if @options[:order]
      output.puts('int GlobalExpectCount;') 
      output.puts('int GlobalVerifyOrder;') 
      output.puts('char* GlobalOrderError;') 
    end
139 140 141 142 143 144 145 146 147
  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|
148
      output.puts("extern void #{test[:name]}(void);")
149 150 151 152 153 154 155 156 157
    end
    output.puts('')
  end
  
  
  def create_mock_management(output, mocks)
    unless (mocks.empty?)
      output.puts("static void CMock_Init(void)")
      output.puts("{")
158
      if @options[:order]
159 160 161
        output.puts("  GlobalExpectCount = 0;")
        output.puts("  GlobalVerifyOrder = 0;") 
        output.puts("  GlobalOrderError = NULL;") 
162
      end
163
      mocks.each do |mock|
164
        output.puts("  #{mock}_Init();")
165 166 167 168 169 170
      end
      output.puts("}\n")

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

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

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

    output.puts()
232 233 234
    output.puts("  UnityEnd();")
    output.puts("  cov_write();") if @options[:coverage]
    output.puts("  return 0;")
235 236 237 238 239 240
    output.puts("}")
  end
end


if ($0 == __FILE__)
241 242
  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)",
243 244
           "  -cexception - include cexception support",
           "  -coverage   - include bullseye coverage support",
245
           "  -order      - include cmock order-enforcement support" ]
246

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