rakefile_helper.rb 9.0 KB
Newer Older
M
Mark VanderVoord 已提交
1 2 3 4 5 6 7 8
# ==========================================
#   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]
# ==========================================

require 'yaml'
require 'fileutils'
J
John Lindgren 已提交
9 10 11
require_relative '../auto/unity_test_summary'
require_relative '../auto/generate_test_runner'
require_relative '../auto/colour_reporter'
M
Mark VanderVoord 已提交
12 13

module RakefileHelpers
14
  C_EXTENSION = '.c'.freeze
M
Mark VanderVoord 已提交
15
  def load_configuration(config_file)
16 17 18 19 20 21
    return if $configured

    $cfg_file = "targets/#{config_file}" unless config_file =~ /[\\|\/]/
    $cfg = YAML.load(File.read($cfg_file))
    $colour_output = false unless $cfg['colour']
    $configured = true if config_file != DEFAULT_CONFIG_FILE
M
Mark VanderVoord 已提交
22 23 24 25 26 27
  end

  def configure_clean
    CLEAN.include($cfg['compiler']['build_path'] + '*.*') unless $cfg['compiler']['build_path'].nil?
  end

28
  def configure_toolchain(config_file = DEFAULT_CONFIG_FILE)
M
Mark VanderVoord 已提交
29 30 31 32 33 34
    config_file += '.yml' unless config_file =~ /\.yml$/
    config_file = config_file unless config_file =~ /[\\|\/]/
    load_configuration(config_file)
    configure_clean
  end

35
  def unit_test_files
M
Mark VanderVoord 已提交
36
    path = $cfg['compiler']['unit_tests_path'] + 'test*' + C_EXTENSION
37
    path.tr!('\\', '/')
M
Mark VanderVoord 已提交
38 39 40
    FileList.new(path)
  end

41
  def local_include_dirs
M
Mark VanderVoord 已提交
42
    include_dirs = $cfg['compiler']['includes']['items'].dup
43 44
    include_dirs.delete_if { |dir| dir.is_a?(Array) }
    include_dirs
M
Mark VanderVoord 已提交
45 46 47 48 49 50 51
  end

  def extract_headers(filename)
    includes = []
    lines = File.readlines(filename)
    lines.each do |line|
      m = line.match(/^\s*#include\s+\"\s*(.+\.[hH])\s*\"/)
52
      includes << m[1] unless m.nil?
M
Mark VanderVoord 已提交
53
    end
54
    includes
M
Mark VanderVoord 已提交
55 56 57 58 59
  end

  def find_source_file(header, paths)
    paths.each do |dir|
      src_file = dir + header.ext(C_EXTENSION)
60
      return src_file if File.exist?(src_file)
M
Mark VanderVoord 已提交
61
    end
62
    nil
M
Mark VanderVoord 已提交
63 64 65
  end

  def tackit(strings)
66 67 68 69 70 71
    result = if strings.is_a?(Array)
               "\"#{strings.join}\""
             else
               strings
             end
    result
M
Mark VanderVoord 已提交
72 73 74 75 76
  end

  def squash(prefix, items)
    result = ''
    items.each { |item| result += " #{prefix}#{tackit(item)}" }
77
    result
M
Mark VanderVoord 已提交
78 79 80 81
  end

  def should(behave, &block)
    if block
82
      puts 'Should ' + behave
M
Mark VanderVoord 已提交
83 84 85 86 87 88
      yield block
    else
      puts "UNIMPLEMENTED CASE: Should #{behave}"
    end
  end

89
  def build_compiler_fields(inject_defines)
90 91 92 93
    command = tackit($cfg['compiler']['path'])
    defines = if $cfg['compiler']['defines']['items'].nil?
                ''
              else
94
                squash($cfg['compiler']['defines']['prefix'], $cfg['compiler']['defines']['items'] + ['UNITY_OUTPUT_CHAR=putcharSpy'] + ['UNITY_OUTPUT_CHAR_HEADER_DECLARATION="putcharSpy(int)"'] + inject_defines)
95 96
              end
    options = squash('', $cfg['compiler']['options'])
M
Mark VanderVoord 已提交
97 98
    includes = squash($cfg['compiler']['includes']['prefix'], $cfg['compiler']['includes']['items'])
    includes = includes.gsub(/\\ /, ' ').gsub(/\\\"/, '"').gsub(/\\$/, '') # Remove trailing slashes (for IAR)
99 100

    { :command => command, :defines => defines, :options => options, :includes => includes }
M
Mark VanderVoord 已提交
101 102
  end

103
  def compile(file, defines = [])
104
    compiler = build_compiler_fields(defines)
105
    cmd_str  = "#{compiler[:command]}#{compiler[:defines]}#{compiler[:options]}#{compiler[:includes]} #{file} " \
M
Mark VanderVoord 已提交
106 107 108
               "#{$cfg['compiler']['object_files']['prefix']}#{$cfg['compiler']['object_files']['destination']}"
    obj_file = "#{File.basename(file, C_EXTENSION)}#{$cfg['compiler']['object_files']['extension']}"
    execute(cmd_str + obj_file)
109 110

    obj_file
M
Mark VanderVoord 已提交
111 112 113
  end

  def build_linker_fields
114 115 116 117 118 119 120 121 122 123 124 125 126
    command = tackit($cfg['linker']['path'])
    options = if $cfg['linker']['options'].nil?
                ''
              else
                squash('', $cfg['linker']['options'])
              end
    includes = if $cfg['linker']['includes'].nil? || $cfg['linker']['includes']['items'].nil?
                 ''
               else
                 squash($cfg['linker']['includes']['prefix'], $cfg['linker']['includes']['items'])
               end.gsub(/\\ /, ' ').gsub(/\\\"/, '"').gsub(/\\$/, '') # Remove trailing slashes (for IAR)

    { :command => command, :options => options, :includes => includes }
M
Mark VanderVoord 已提交
127 128 129 130 131
  end

  def link_it(exe_name, obj_list)
    linker = build_linker_fields
    cmd_str = "#{linker[:command]}#{linker[:options]}#{linker[:includes]} " +
132 133 134 135
              (obj_list.map { |obj| "#{$cfg['linker']['object_files']['path']}#{obj} " }).join +
              $cfg['linker']['bin_files']['prefix'] + ' ' +
              $cfg['linker']['bin_files']['destination'] +
              exe_name + $cfg['linker']['bin_files']['extension']
M
Mark VanderVoord 已提交
136 137 138 139 140
    execute(cmd_str)
  end

  def build_simulator_fields
    return nil if $cfg['simulator'].nil?
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
    command = if $cfg['simulator']['path'].nil?
                ''
              else
                (tackit($cfg['simulator']['path']) + ' ')
              end
    pre_support = if $cfg['simulator']['pre_support'].nil?
                    ''
                  else
                    squash('', $cfg['simulator']['pre_support'])
                  end
    post_support = if $cfg['simulator']['post_support'].nil?
                     ''
                   else
                     squash('', $cfg['simulator']['post_support'])
                   end

    { :command => command, :pre_support => pre_support, :post_support => post_support }
  end

160 161 162 163 164 165 166 167 168 169 170 171
  def run_astyle(style_what)
    report "Styling C Code..."
    command = "AStyle " \
              "--style=allman --indent=spaces=4 --indent-switches --indent-preproc-define --indent-preproc-block " \
              "--pad-oper --pad-comma --unpad-paren --pad-header " \
              "--align-pointer=type --align-reference=name " \
              "--add-brackets --mode=c --suffix=none " \
              "#{style_what}"
    execute(command, false)
    report "Styling C:PASS"
  end

172
  def execute(command_string, ok_to_fail = false)
173
    report command_string if $verbose
M
Mark VanderVoord 已提交
174
    output = `#{command_string}`.chomp
175
    report(output) if $verbose && !output.nil? && !output.empty?
176
    raise "Command failed. (Returned #{$?.exitstatus})" if !$?.nil? && !$?.exitstatus.zero? && !ok_to_fail
177
    output
M
Mark VanderVoord 已提交
178 179 180 181
  end

  def report_summary
    summary = UnityTestSummary.new
J
John Lindgren 已提交
182
    summary.root = __dir__
M
Mark VanderVoord 已提交
183
    results_glob = "#{$cfg['compiler']['build_path']}*.test*"
184
    results_glob.tr!('\\', '/')
M
Mark VanderVoord 已提交
185
    results = Dir[results_glob]
186
    summary.targets = results
M
Mark VanderVoord 已提交
187 188 189 190 191 192 193 194 195
    report summary.run
  end

  def run_tests(test_files)
    report 'Running Unity system tests...'

    # Tack on TEST define for compiling unit tests
    load_configuration($cfg_file)
    test_defines = ['TEST']
196
    $cfg['compiler']['defines']['items'] ||= []
M
Mark VanderVoord 已提交
197 198
    $cfg['compiler']['defines']['items'] << 'TEST'

199
    include_dirs = local_include_dirs
M
Mark VanderVoord 已提交
200 201 202

    # Build and execute each unit test
    test_files.each do |test|
203 204 205 206 207 208 209 210 211

      # Drop Out if we're skipping this type of test
      if $cfg[:skip_tests]
        if $cfg[:skip_tests].include?(:parameterized) && test.match(/parameterized/)
          report("Skipping Parameterized Tests for this Target:IGNORE")
          next
        end
      end

M
Mark VanderVoord 已提交
212 213
      obj_list = []

214
      unless $cfg['compiler']['aux_sources'].nil?
M
Mark VanderVoord 已提交
215 216 217 218 219 220 221 222 223
        $cfg['compiler']['aux_sources'].each do |aux|
          obj_list << compile(aux, test_defines)
        end
      end

      # Detect dependencies and build required modules
      extract_headers(test).each do |header|
        # Compile corresponding source file if it exists
        src_file = find_source_file(header, include_dirs)
224 225

        obj_list << compile(src_file, test_defines) unless src_file.nil?
M
Mark VanderVoord 已提交
226 227 228 229 230 231 232
      end

      # Build the test runner (generate if configured to do so)
      test_base = File.basename(test, C_EXTENSION)

      runner_name = test_base + '_Runner.c'

233 234 235 236 237
      runner_path = if $cfg['compiler']['runner_path'].nil?
                      $cfg['compiler']['build_path'] + runner_name
                    else
                      $cfg['compiler']['runner_path'] + runner_name
                    end
M
Mark VanderVoord 已提交
238 239

      options = $cfg[:unity]
240
      options[:use_param_tests] = test =~ /parameterized/ ? true : false
M
Mark VanderVoord 已提交
241 242 243 244 245 246 247 248 249 250 251 252
      UnityTestRunnerGenerator.new(options).run(test, runner_path)
      obj_list << compile(runner_path, test_defines)

      # Build the test module
      obj_list << compile(test, test_defines)

      # Link the test executable
      link_it(test_base, obj_list)

      # Execute unit test and generate results file
      simulator = build_simulator_fields
      executable = $cfg['linker']['bin_files']['destination'] + test_base + $cfg['linker']['bin_files']['extension']
253 254 255 256 257
      cmd_str = if simulator.nil?
                  executable
                else
                  "#{simulator[:command]} #{simulator[:pre_support]} #{executable} #{simulator[:post_support]}"
                end
M
Mark VanderVoord 已提交
258 259 260 261 262
      output = execute(cmd_str)
      test_results = $cfg['compiler']['build_path'] + test_base
      if output.match(/OK$/m).nil?
        test_results += '.testfail'
      else
263
        report output unless $verbose # Verbose already prints this line, as does a failure
M
Mark VanderVoord 已提交
264 265 266 267 268 269
        test_results += '.testpass'
      end
      File.open(test_results, 'w') { |f| f.print output }
    end
  end
end