Debian Codegraph @

test/rakefile_helper.rb

raw symbols SCIP
1 # ==========================================
2 # CMock Project - Automatic Mock Generation for C
3 # Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams
4 # [Released under MIT License. Please refer to license.txt for details]
5 # ==========================================
6
7 require 'yaml'
8 require 'fileutils'
9 require '../vendor/unity/auto/generate_test_runner'
10 require '../vendor/unity/auto/unity_test_summary'
11 require '../vendor/unity/auto/colour_reporter.rb'
12 require './system/systest_generator'
13
14 module RakefileHelpers
15
16 SYSTEST_GENERATED_FILES_PATH = './system/generated/'
17 SYSTEST_BUILD_FILES_PATH = './system/build/'
18 SYSTEST_COMPILE_MOCKABLES_PATH = './system/test_compilation/'
19 C_EXTENSION = '.c'
20 RESULT_EXTENSION = '.result'
21
22 def load_configuration(config_file)
23 $cfg_file = config_file
24 $cfg = YAML.load(File.read('./targets/' + $cfg_file))
25 $colour_output = false unless $cfg['colour']
26 end
27
28 def configure_clean
29 CLEAN.include(SYSTEST_GENERATED_FILES_PATH + '*.*')
30 CLEAN.include(SYSTEST_BUILD_FILES_PATH + '*.*')
31 end
32
33 def configure_toolchain(config_file)
34 load_configuration(config_file)
35 configure_clean
36 end
37
38 def get_local_include_dirs
39 include_dirs = $cfg['compiler']['includes']['items'].dup
40 include_dirs.delete_if {|dir| dir.is_a?(Array)}
41 return include_dirs
42 end
43
44 def extract_headers(filename)
45 includes = []
46 lines = File.readlines(filename)
47 lines.each do |line|
48 m = line.match(/^\s*#include\s+\"\s*(.+\.[hH])\s*\"/)
49 if not m.nil?
50 includes << m[1]
51 end
52 end
53 includes << File.basename(filename,".c").slice(5,256) + "_unity_helper.h"
54 return includes
55 end
56
57 def find_source_file(header, paths)
58 paths.each do |dir|
59 src_file = dir + header.ext(C_EXTENSION)
60 if (File.exists?(src_file))
61 return src_file
62 end
63 end
64 return nil
65 end
66
67 def squash(prefix, items)
68 result = ''
69 items.each { |item| result += " #{prefix}#{tackit(item)}" }
70 return result
71 end
72
73 def build_compiler_fields
74 command = tackit($cfg['compiler']['path'])
75 if $cfg['compiler']['defines']['items'].nil?
76 defines = ''
77 else
78 defines = squash($cfg['compiler']['defines']['prefix'], $cfg['compiler']['defines']['items'])
79 end
80 options = squash('', $cfg['compiler']['options'])
81 includes = squash($cfg['compiler']['includes']['prefix'], $cfg['compiler']['includes']['items'])
82 includes = includes.gsub(/\\ /, ' ').gsub(/\\\"/, '"').gsub(/\\$/, '') # Remove trailing slashes (for IAR)
83 return {:command => command, :defines => defines, :options => options, :includes => includes}
84 end
85
86 def compile(file, defines=[])
87 compiler = build_compiler_fields
88 cmd_str = "#{compiler[:command]}#{compiler[:defines]}#{defines.inject(''){|all, a| ' -D'+a+all }}#{compiler[:options]}#{compiler[:includes]} #{file} " +
89 "#{$cfg['compiler']['object_files']['prefix']}#{$cfg['compiler']['object_files']['destination']}"
90 obj_file = "#{File.basename(file, C_EXTENSION)}#{$cfg['compiler']['object_files']['extension']}"
91 execute(cmd_str + obj_file)
92 return obj_file
93 end
94
95 def build_linker_fields
96 command = tackit($cfg['linker']['path'])
97 if $cfg['linker']['options'].nil?
98 options = ''
99 else
100 options = squash('', $cfg['linker']['options'])
101 end
102 if ($cfg['linker']['includes'].nil? || $cfg['linker']['includes']['items'].nil?)
103 includes = ''
104 else
105 includes = squash($cfg['linker']['includes']['prefix'], $cfg['linker']['includes']['items'])
106 end
107 includes = includes.gsub(/\\ /, ' ').gsub(/\\\"/, '"').gsub(/\\$/, '') # Remove trailing slashes (for IAR)
108 return {:command => command, :options => options, :includes => includes}
109 end
110
111 def link_it(exe_name, obj_list)
112 linker = build_linker_fields
113 cmd_str = "#{linker[:command]}#{linker[:options]}#{linker[:includes]} " +
114 (obj_list.map{|obj|"#{$cfg['linker']['object_files']['path']}#{obj} "}).uniq.join +
115 $cfg['linker']['bin_files']['prefix'] + ' ' +
116 $cfg['linker']['bin_files']['destination'] +
117 exe_name + $cfg['linker']['bin_files']['extension']
118 execute(cmd_str)
119 end
120
121 def build_simulator_fields
122 return nil if $cfg['simulator'].nil?
123 if $cfg['simulator']['path'].nil?
124 command = ''
125 else
126 command = (tackit($cfg['simulator']['path']) + ' ')
127 end
128 if $cfg['simulator']['pre_support'].nil?
129 pre_support = ''
130 else
131 pre_support = squash('', $cfg['simulator']['pre_support'])
132 end
133 if $cfg['simulator']['post_support'].nil?
134 post_support = ''
135 else
136 post_support = squash('', $cfg['simulator']['post_support'])
137 end
138 return {:command => command, :pre_support => pre_support, :post_support => post_support}
139 end
140
141 def execute(command_string, verbose=true, raise_on_failure=true)
142 #report command_string
143 output = `#{command_string}`.chomp
144 report(output) if (verbose && !output.nil? && (output.length > 0))
145 if ($?.exitstatus != 0) and (raise_on_failure)
146 raise "#{command_string} failed. (Returned #{$?.exitstatus})"
147 end
148 return output
149 end
150
151 def tackit(strings)
152 case(strings)
153 when Array
154 "\"#{strings.join}\""
155 when /^-/
156 strings
157 when /\s/
158 "\"#{strings}\""
159 else
160 strings
161 end
162 end
163
164 def run_astyle(style_what)
165 report "Styling C Code..."
166 command = "AStyle " \
167 "--style=allman --indent=spaces=4 --indent-switches --indent-preproc-define --indent-preproc-block " \
168 "--pad-oper --pad-comma --unpad-paren --pad-header " \
169 "--align-pointer=type --align-reference=name " \
170 "--add-brackets --mode=c --suffix=none " \
171 "#{style_what}"
172 execute(command, false)
173 report "Styling C:PASS"
174 end
175
176 def report_summary
177 summary = UnityTestSummary.new
178 summary.root = File.expand_path(File.dirname(__FILE__)) + '/'
179 results_glob = "#{$cfg['compiler']['build_path']}*.test*"
180 results_glob.gsub!(/\\/, '/')
181 results = Dir[results_glob]
182 summary.targets = results
183 summary.run
184 fail_out "FAIL: There were failures" if (summary.failures > 0)
185 end
186
187 def run_system_test_interactions(test_case_files)
188 load '../lib/cmock.rb'
189
190 SystemTestGenerator.new.generate_files(test_case_files)
191 test_files = FileList.new(SYSTEST_GENERATED_FILES_PATH + 'test*.c')
192
193 load_configuration($cfg_file)
194 $cfg['compiler']['defines']['items'] = [] if $cfg['compiler']['defines']['items'].nil?
195
196 include_dirs = get_local_include_dirs
197
198 # Build and execute each unit test
199 test_files.each do |test|
200
201 obj_list = []
202
203 test_base = File.basename(test, C_EXTENSION)
204 cmock_config = test_base.gsub(/test_/, '') + '_cmock.yml'
205
206 report "Executing system tests in #{File.basename(test)}..."
207
208 # Detect dependencies and build required required modules
209 extract_headers(test).each do |header|
210
211 # Generate any needed mocks
212 if header =~ /^mock_(.*)\.h/i
213 module_name = $1
214 cmock = CMock.new(SYSTEST_GENERATED_FILES_PATH + cmock_config)
215 cmock.setup_mocks("#{$cfg['compiler']['source_path']}#{module_name}.h")
216 end
217 # Compile corresponding source file if it exists
218 src_file = find_source_file(header, include_dirs)
219 if !src_file.nil?
220 obj_list << compile(src_file)
221 end
222 end
223
224 # Generate and build the test suite runner
225 runner_name = test_base + '_runner.c'
226 runner_path = $cfg['compiler']['source_path'] + runner_name
227 UnityTestRunnerGenerator.new(SYSTEST_GENERATED_FILES_PATH + cmock_config).run(test, runner_path)
228 obj_list << compile(runner_path)
229
230 # Build the test module
231 obj_list << compile(test)
232
233 # Link the test executable
234 link_it(test_base, obj_list)
235
236 # Execute unit test and generate results file
237 simulator = build_simulator_fields
238 executable = $cfg['linker']['bin_files']['destination'] + test_base + $cfg['linker']['bin_files']['extension']
239 if simulator.nil?
240 cmd_str = executable
241 else
242 cmd_str = "#{simulator[:command]} #{simulator[:pre_support]} #{executable} #{simulator[:post_support]}"
243 end
244 output = execute(cmd_str, false, false)
245 test_results = $cfg['compiler']['build_path'] + test_base + RESULT_EXTENSION
246 File.open(test_results, 'w') { |f| f.print output }
247 end
248
249 # Parse and report test results
250 total_tests = 0
251 total_failures = 0
252 failure_messages = []
253
254 test_case_files.each do |test_case|
255 tests = (YAML.load_file(test_case))[:systest][:tests][:units]
256 total_tests += tests.size
257
258 test_file = 'test_' + File.basename(test_case).ext(C_EXTENSION)
259 result_file = test_file.ext(RESULT_EXTENSION)
260 test_results = File.readlines(SYSTEST_BUILD_FILES_PATH + result_file).reject {|line| line.size < 10 } # we're rejecting lines that are too short to be realistic, which handles line ending problems
261 tests.each_with_index do |test, index|
262 # compare test's intended pass/fail state with pass/fail state in actual results;
263 # if they don't match, the system test has failed
264 this_failed = case(test[:pass])
265 when :ignore
266 (test_results[index] =~ /:IGNORE/).nil?
267 when true
268 (test_results[index] =~ /:PASS/).nil?
269 when false
270 (test_results[index] =~ /:FAIL/).nil?
271 end
272 if (this_failed)
273 total_failures += 1
274 test_results[index] =~ /test#{index+1}:(.+)/
275 failure_messages << "#{test_file}:test#{index+1}:should #{test[:should]}:#{$1}"
276 end
277 # some tests have additional requirements to check for (checking the actual output message)
278 if (test[:verify_error]) and not (test_results[index] =~ /test#{index+1}:.*#{test[:verify_error]}/)
279 total_failures += 1
280 failure_messages << "#{test_file}:test#{index+1}:should #{test[:should]}:should have output matching '#{test[:verify_error]}' but was '#{test_results[index]}'"
281 end
282 end
283 end
284
285 report "\n"
286 report "------------------------------------\n"
287 report "SYSTEM TEST MOCK INTERACTION SUMMARY\n"
288 report "------------------------------------\n"
289 report "#{total_tests} Tests #{total_failures} Failures 0 Ignored\n"
290 report "\n"
291
292 if (failure_messages.size > 0)
293 report 'System test failures:'
294 failure_messages.each do |failure|
295 report failure
296 end
297 end
298
299 report ''
300
301 return total_failures
302 end
303
304 def profile_this(filename)
305 profile = true
306 begin
307 require 'ruby-prof'
308 RubyProf.start
309 rescue
310 profile = false
311 end
312
313 yield
314
315 if (profile)
316 profile_result = RubyProf.stop
317 File.open("Profile_#{filename}.html", 'w') do |f|
318 RubyProf::GraphHtmlPrinter.new(profile_result).print(f)
319 end
320 end
321 end
322
323 def run_system_test_compilations(mockables)
324 load '../lib/cmock.rb'
325
326 load_configuration($cfg_file)
327 $cfg['compiler']['defines']['items'] = [] if $cfg['compiler']['defines']['items'].nil?
328
329 report "\n"
330 report "------------------------------------\n"
331 report "SYSTEM TEST MOCK COMPILATION SUMMARY\n"
332 report "------------------------------------\n"
333 mockables.each do |header|
334 mock_filename = 'mock_' + File.basename(header).ext('.c')
335 CMock.new(SYSTEST_COMPILE_MOCKABLES_PATH + 'config.yml').setup_mocks(header)
336 report "Compiling #{mock_filename}..."
337 compile(SYSTEST_GENERATED_FILES_PATH + mock_filename)
338 end
339 end
340
341 def run_system_test_profiles(mockables)
342 load '../lib/cmock.rb'
343
344 load_configuration($cfg_file)
345 $cfg['compiler']['defines']['items'] = [] if $cfg['compiler']['defines']['items'].nil?
346
347 report "\n"
348 report "--------------------------\n"
349 report "SYSTEM TEST MOCK PROFILING\n"
350 report "--------------------------\n"
351 mockables.each do |header|
352 mock_filename = 'mock_' + File.basename(header).ext('.c')
353 profile_this(mock_filename.gsub('.c','')) do
354 10.times do
355 CMock.new(SYSTEST_COMPILE_MOCKABLES_PATH + 'config.yml').setup_mocks(header)
356 end
357 end
358 report "Compiling #{mock_filename}..."
359 compile(SYSTEST_GENERATED_FILES_PATH + mock_filename)
360 end
361 end
362
363 def build_and_test_c_files
364 report "\n"
365 report "----------------\n"
366 report "UNIT TEST C CODE\n"
367 report "----------------\n"
368 errors = false
369 FileList.new("c/*.yml").each do |yaml_file|
370 test = YAML.load(File.read(yaml_file))
371 report "\nTesting #{yaml_file.sub('.yml','')}"
372 report "(#{test[:options].join(', ')})"
373 test[:files].each { |f| compile(f, test[:options]) }
374 obj_files = test[:files].map { |f| f.gsub!(/.*\//,'').gsub!(C_EXTENSION, $cfg['compiler']['object_files']['extension']) }
375 link_it('TestCMockC', obj_files)
376 if $cfg['simulator'].nil?
377 execute($cfg['linker']['bin_files']['destination'] + 'TestCMockC' + $cfg['linker']['bin_files']['extension'])
378 else
379 execute(tackit($cfg['simulator']['path'].join) + ' ' +
380 $cfg['simulator']['pre_support'].map{|o| tackit(o)}.join(' ') + ' ' +
381 $cfg['linker']['bin_files']['destination'] +
382 'TestCMockC' +
383 $cfg['linker']['bin_files']['extension'] + ' ' +
384 $cfg['simulator']['post_support'].map{|o| tackit(o)}.join(' ') )
385 end
386 end
387 end
388
389 def run_examples()
390 [ "cd #{File.join("..","examples","make_example")} && make clean && make setup && make test",
391 "cd #{File.join("..","examples","temp_sensor")} && rake ci"
392 ].each do |cmd|
393 report "Testing '#{cmd}'"
394 execute(cmd, false)
395 end
396 end
397
398 def fail_out(msg)
399 puts msg
400 exit(-1)
401 end
402 end
403