Debian Codegraph @

vendor/unity/auto/generate_test_runner.rb

raw
1 # ==========================================
2 # Unity Project - A Test Framework 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 class UnityTestRunnerGenerator
8 def initialize(options = nil)
9 @options = UnityTestRunnerGenerator.default_options
10 case options
11 when NilClass
12 @options
13 when String
14 @options.merge!(UnityTestRunnerGenerator.grab_config(options))
15 when Hash
16 # Check if some of these have been specified
17 @options[:has_setup] = !options[:setup_name].nil?
18 @options[:has_teardown] = !options[:teardown_name].nil?
19 @options[:has_suite_setup] = !options[:suite_setup].nil?
20 @options[:has_suite_teardown] = !options[:suite_teardown].nil?
21 @options.merge!(options)
22 else
23 raise 'If you specify arguments, it should be a filename or a hash of options'
24 end
25 require_relative 'type_sanitizer'
26 end
27
28 def self.default_options
29 {
30 includes: [],
31 defines: [],
32 plugins: [],
33 framework: :unity,
34 test_prefix: 'test|spec|should',
35 mock_prefix: 'Mock',
36 mock_suffix: '',
37 setup_name: 'setUp',
38 teardown_name: 'tearDown',
39 test_reset_name: 'resetTest',
40 test_verify_name: 'verifyTest',
41 main_name: 'main', # set to :auto to automatically generate each time
42 main_export_decl: '',
43 cmdline_args: false,
44 omit_begin_end: false,
45 use_param_tests: false,
46 include_extensions: '(?:hpp|hh|H|h)',
47 source_extensions: '(?:cpp|cc|ino|C|c)'
48 }
49 end
50
51 def self.grab_config(config_file)
52 options = default_options
53 unless config_file.nil? || config_file.empty?
54 require 'yaml'
55 yaml_guts = YAML.load_file(config_file)
56 options.merge!(yaml_guts[:unity] || yaml_guts[:cmock])
57 raise "No :unity or :cmock section found in #{config_file}" unless options
58 end
59 options
60 end
61
62 def run(input_file, output_file, options = nil)
63 @options.merge!(options) unless options.nil?
64
65 # pull required data from source file
66 source = File.read(input_file)
67 source = source.force_encoding('ISO-8859-1').encode('utf-8', replace: nil)
68 tests = find_tests(source)
69 headers = find_includes(source)
70 testfile_includes = (headers[:local] + headers[:system])
71 used_mocks = find_mocks(testfile_includes)
72 testfile_includes = (testfile_includes - used_mocks)
73 testfile_includes.delete_if { |inc| inc =~ /(unity|cmock)/ }
74 find_setup_and_teardown(source)
75
76 # build runner file
77 generate(input_file, output_file, tests, used_mocks, testfile_includes)
78
79 # determine which files were used to return them
80 all_files_used = [input_file, output_file]
81 all_files_used += testfile_includes.map { |filename| filename + '.c' } unless testfile_includes.empty?
82 all_files_used += @options[:includes] unless @options[:includes].empty?
83 all_files_used += headers[:linkonly] unless headers[:linkonly].empty?
84 all_files_used.uniq
85 end
86
87 def generate(input_file, output_file, tests, used_mocks, testfile_includes)
88 File.open(output_file, 'w') do |output|
89 create_header(output, used_mocks, testfile_includes)
90 create_externs(output, tests, used_mocks)
91 create_mock_management(output, used_mocks)
92 create_setup(output)
93 create_teardown(output)
94 create_suite_setup(output)
95 create_suite_teardown(output)
96 create_reset(output)
97 create_run_test(output) unless tests.empty?
98 create_args_wrappers(output, tests)
99 create_main(output, input_file, tests, used_mocks)
100 end
101
102 return unless @options[:header_file] && !@options[:header_file].empty?
103
104 File.open(@options[:header_file], 'w') do |output|
105 create_h_file(output, @options[:header_file], tests, testfile_includes, used_mocks)
106 end
107 end
108
109 def find_tests(source)
110 tests_and_line_numbers = []
111
112 # contains characters which will be substituted from within strings, doing
113 # this prevents these characters from interfering with scrubbers
114 # @ is not a valid C character, so there should be no clashes with files genuinely containing these markers
115 substring_subs = { '{' => '@co@', '}' => '@cc@', ';' => '@ss@', '/' => '@fs@' }
116 substring_re = Regexp.union(substring_subs.keys)
117 substring_unsubs = substring_subs.invert # the inverse map will be used to fix the strings afterwords
118 substring_unsubs['@quote@'] = '\\"'
119 substring_unsubs['@apos@'] = '\\\''
120 substring_unre = Regexp.union(substring_unsubs.keys)
121 source_scrubbed = source.clone
122 source_scrubbed = source_scrubbed.gsub(/\\"/, '@quote@') # hide escaped quotes to allow capture of the full string/char
123 source_scrubbed = source_scrubbed.gsub(/\\'/, '@apos@') # hide escaped apostrophes to allow capture of the full string/char
124 source_scrubbed = source_scrubbed.gsub(/("[^"\n]*")|('[^'\n]*')/) { |s| s.gsub(substring_re, substring_subs) } # temporarily hide problematic characters within strings
125 source_scrubbed = source_scrubbed.gsub(/\/\/(?:.+\/\*|\*(?:$|[^\/])).*$/, '') # remove line comments that comment out the start of blocks
126 source_scrubbed = source_scrubbed.gsub(/\/\*.*?\*\//m, '') # remove block comments
127 source_scrubbed = source_scrubbed.gsub(/\/\/.*$/, '') # remove line comments (all that remain)
128 lines = source_scrubbed.split(/(^\s*\#.*$) | (;|\{|\}) /x) # Treat preprocessor directives as a logical line. Match ;, {, and } as end of lines
129 .map { |line| line.gsub(substring_unre, substring_unsubs) } # unhide the problematic characters previously removed
130
131 lines.each_with_index do |line, _index|
132 # find tests
133 next unless line =~ /^((?:\s*(?:TEST_CASE|TEST_RANGE)\s*\(.*?\)\s*)*)\s*void\s+((?:#{@options[:test_prefix]}).*)\s*\(\s*(.*)\s*\)/m
134
135 arguments = Regexp.last_match(1)
136 name = Regexp.last_match(2)
137 call = Regexp.last_match(3)
138 params = Regexp.last_match(4)
139 args = nil
140
141 if @options[:use_param_tests] && !arguments.empty?
142 args = []
143 arguments.scan(/\s*TEST_CASE\s*\((.*)\)\s*$/) { |a| args << a[0] }
144
145 arguments.scan(/\s*TEST_RANGE\s*\((.*)\)\s*$/).flatten.each do |range_str|
146 args += range_str.scan(/\[\s*(-?\d+.?\d*),\s*(-?\d+.?\d*),\s*(-?\d+.?\d*)\s*\]/).map do |arg_values_str|
147 arg_values_str.map do |arg_value_str|
148 arg_value_str.include?('.') ? arg_value_str.to_f : arg_value_str.to_i
149 end
150 end.map do |arg_values|
151 (arg_values[0]..arg_values[1]).step(arg_values[2]).to_a
152 end.reduce do |result, arg_range_expanded|
153 result.product(arg_range_expanded)
154 end.map do |arg_combinations|
155 arg_combinations.flatten.join(', ')
156 end
157 end
158 end
159
160 tests_and_line_numbers << { test: name, args: args, call: call, params: params, line_number: 0 }
161 end
162
163 tests_and_line_numbers.uniq! { |v| v[:test] }
164
165 # determine line numbers and create tests to run
166 source_lines = source.split("\n")
167 source_index = 0
168 tests_and_line_numbers.size.times do |i|
169 source_lines[source_index..-1].each_with_index do |line, index|
170 next unless line =~ /\s+#{tests_and_line_numbers[i][:test]}(?:\s|\()/
171
172 source_index += index
173 tests_and_line_numbers[i][:line_number] = source_index + 1
174 break
175 end
176 end
177
178 tests_and_line_numbers
179 end
180
181 def find_includes(source)
182 # remove comments (block and line, in three steps to ensure correct precedence)
183 source.gsub!(/\/\/(?:.+\/\*|\*(?:$|[^\/])).*$/, '') # remove line comments that comment out the start of blocks
184 source.gsub!(/\/\*.*?\*\//m, '') # remove block comments
185 source.gsub!(/\/\/.*$/, '') # remove line comments (all that remain)
186
187 # parse out includes
188 includes = {
189 local: source.scan(/^\s*#include\s+\"\s*(.+\.#{@options[:include_extensions]})\s*\"/).flatten,
190 system: source.scan(/^\s*#include\s+<\s*(.+)\s*>/).flatten.map { |inc| "<#{inc}>" },
191 linkonly: source.scan(/^TEST_FILE\(\s*\"\s*(.+\.#{@options[:source_extensions]})\s*\"/).flatten
192 }
193 includes
194 end
195
196 def find_mocks(includes)
197 mock_headers = []
198 includes.each do |include_path|
199 include_file = File.basename(include_path)
200 mock_headers << include_path if include_file =~ /^#{@options[:mock_prefix]}.*#{@options[:mock_suffix]}\.h$/i
201 end
202 mock_headers
203 end
204
205 def find_setup_and_teardown(source)
206 @options[:has_setup] = source =~ /void\s+#{@options[:setup_name]}\s*\(/
207 @options[:has_teardown] = source =~ /void\s+#{@options[:teardown_name]}\s*\(/
208 @options[:has_suite_setup] ||= (source =~ /void\s+suiteSetUp\s*\(/)
209 @options[:has_suite_teardown] ||= (source =~ /int\s+suiteTearDown\s*\(int\s+([a-zA-Z0-9_])+\s*\)/)
210 end
211
212 def create_header(output, mocks, testfile_includes = [])
213 output.puts('/* AUTOGENERATED FILE. DO NOT EDIT. */')
214 output.puts("\n/*=======Automagically Detected Files To Include=====*/")
215 output.puts('extern "C" {') if @options[:externcincludes]
216 output.puts("#include \"#{@options[:framework]}.h\"")
217 output.puts('#include "cmock.h"') unless mocks.empty?
218 output.puts('}') if @options[:externcincludes]
219 if @options[:defines] && !@options[:defines].empty?
220 @options[:defines].each { |d| output.puts("#ifndef #{d}\n#define #{d}\n#endif /* #{d} */") }
221 end
222 if @options[:header_file] && !@options[:header_file].empty?
223 output.puts("#include \"#{File.basename(@options[:header_file])}\"")
224 else
225 @options[:includes].flatten.uniq.compact.each do |inc|
226 output.puts("#include #{inc.include?('<') ? inc : "\"#{inc}\""}")
227 end
228 testfile_includes.each do |inc|
229 output.puts("#include #{inc.include?('<') ? inc : "\"#{inc}\""}")
230 end
231 end
232 output.puts('extern "C" {') if @options[:externcincludes]
233 mocks.each do |mock|
234 output.puts("#include \"#{mock}\"")
235 end
236 output.puts('}') if @options[:externcincludes]
237 output.puts('#include "CException.h"') if @options[:plugins].include?(:cexception)
238
239 return unless @options[:enforce_strict_ordering]
240
241 output.puts('')
242 output.puts('int GlobalExpectCount;')
243 output.puts('int GlobalVerifyOrder;')
244 output.puts('char* GlobalOrderError;')
245 end
246
247 def create_externs(output, tests, _mocks)
248 output.puts("\n/*=======External Functions This Runner Calls=====*/")
249 output.puts("extern void #{@options[:setup_name]}(void);")
250 output.puts("extern void #{@options[:teardown_name]}(void);")
251 output.puts("\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif") if @options[:externc]
252 tests.each do |test|
253 output.puts("extern void #{test[:test]}(#{test[:call] || 'void'});")
254 end
255 output.puts("#ifdef __cplusplus\n}\n#endif") if @options[:externc]
256 output.puts('')
257 end
258
259 def create_mock_management(output, mock_headers)
260 output.puts("\n/*=======Mock Management=====*/")
261 output.puts('static void CMock_Init(void)')
262 output.puts('{')
263
264 if @options[:enforce_strict_ordering]
265 output.puts(' GlobalExpectCount = 0;')
266 output.puts(' GlobalVerifyOrder = 0;')
267 output.puts(' GlobalOrderError = NULL;')
268 end
269
270 mocks = mock_headers.map { |mock| File.basename(mock, '.*') }
271 mocks.each do |mock|
272 mock_clean = TypeSanitizer.sanitize_c_identifier(mock)
273 output.puts(" #{mock_clean}_Init();")
274 end
275 output.puts("}\n")
276
277 output.puts('static void CMock_Verify(void)')
278 output.puts('{')
279 mocks.each do |mock|
280 mock_clean = TypeSanitizer.sanitize_c_identifier(mock)
281 output.puts(" #{mock_clean}_Verify();")
282 end
283 output.puts("}\n")
284
285 output.puts('static void CMock_Destroy(void)')
286 output.puts('{')
287 mocks.each do |mock|
288 mock_clean = TypeSanitizer.sanitize_c_identifier(mock)
289 output.puts(" #{mock_clean}_Destroy();")
290 end
291 output.puts("}\n")
292 end
293
294 def create_setup(output)
295 return if @options[:has_setup]
296
297 output.puts("\n/*=======Setup (stub)=====*/")
298 output.puts("void #{@options[:setup_name]}(void) {}")
299 end
300
301 def create_teardown(output)
302 return if @options[:has_teardown]
303
304 output.puts("\n/*=======Teardown (stub)=====*/")
305 output.puts("void #{@options[:teardown_name]}(void) {}")
306 end
307
308 def create_suite_setup(output)
309 return if @options[:suite_setup].nil?
310
311 output.puts("\n/*=======Suite Setup=====*/")
312 output.puts('void suiteSetUp(void)')
313 output.puts('{')
314 output.puts(@options[:suite_setup])
315 output.puts('}')
316 end
317
318 def create_suite_teardown(output)
319 return if @options[:suite_teardown].nil?
320
321 output.puts("\n/*=======Suite Teardown=====*/")
322 output.puts('int suiteTearDown(int num_failures)')
323 output.puts('{')
324 output.puts(@options[:suite_teardown])
325 output.puts('}')
326 end
327
328 def create_reset(output)
329 output.puts("\n/*=======Test Reset Options=====*/")
330 output.puts("void #{@options[:test_reset_name]}(void);")
331 output.puts("void #{@options[:test_reset_name]}(void)")
332 output.puts('{')
333 output.puts(" #{@options[:teardown_name]}();")
334 output.puts(' CMock_Verify();')
335 output.puts(' CMock_Destroy();')
336 output.puts(' CMock_Init();')
337 output.puts(" #{@options[:setup_name]}();")
338 output.puts('}')
339 output.puts("void #{@options[:test_verify_name]}(void);")
340 output.puts("void #{@options[:test_verify_name]}(void)")
341 output.puts('{')
342 output.puts(' CMock_Verify();')
343 output.puts('}')
344 end
345
346 def create_run_test(output)
347 require 'erb'
348 template = ERB.new(File.read(File.join(__dir__, 'run_test.erb')), nil, '<>')
349 output.puts("\n" + template.result(binding))
350 end
351
352 def create_args_wrappers(output, tests)
353 return unless @options[:use_param_tests]
354
355 output.puts("\n/*=======Parameterized Test Wrappers=====*/")
356 tests.each do |test|
357 next if test[:args].nil? || test[:args].empty?
358
359 test[:args].each.with_index(1) do |args, idx|
360 output.puts("static void runner_args#{idx}_#{test[:test]}(void)")
361 output.puts('{')
362 output.puts(" #{test[:test]}(#{args});")
363 output.puts("}\n")
364 end
365 end
366 end
367
368 def create_main(output, filename, tests, used_mocks)
369 output.puts("\n/*=======MAIN=====*/")
370 main_name = @options[:main_name].to_sym == :auto ? "main_#{filename.gsub('.c', '')}" : (@options[:main_name]).to_s
371 if @options[:cmdline_args]
372 if main_name != 'main'
373 output.puts("#{@options[:main_export_decl]} int #{main_name}(int argc, char** argv);")
374 end
375 output.puts("#{@options[:main_export_decl]} int #{main_name}(int argc, char** argv)")
376 output.puts('{')
377 output.puts(' int parse_status = UnityParseOptions(argc, argv);')
378 output.puts(' if (parse_status != 0)')
379 output.puts(' {')
380 output.puts(' if (parse_status < 0)')
381 output.puts(' {')
382 output.puts(" UnityPrint(\"#{filename.gsub('.c', '')}.\");")
383 output.puts(' UNITY_PRINT_EOL();')
384 tests.each do |test|
385 if (!@options[:use_param_tests]) || test[:args].nil? || test[:args].empty?
386 output.puts(" UnityPrint(\" #{test[:test]}\");")
387 output.puts(' UNITY_PRINT_EOL();')
388 else
389 test[:args].each do |args|
390 output.puts(" UnityPrint(\" #{test[:test]}(#{args})\");")
391 output.puts(' UNITY_PRINT_EOL();')
392 end
393 end
394 end
395 output.puts(' return 0;')
396 output.puts(' }')
397 output.puts(' return parse_status;')
398 output.puts(' }')
399 else
400 main_return = @options[:omit_begin_end] ? 'void' : 'int'
401 if main_name != 'main'
402 output.puts("#{@options[:main_export_decl]} #{main_return} #{main_name}(void);")
403 end
404 output.puts("#{main_return} #{main_name}(void)")
405 output.puts('{')
406 end
407 output.puts(' suiteSetUp();') if @options[:has_suite_setup]
408 if @options[:omit_begin_end]
409 output.puts(" UnitySetTestFile(\"#{filename.gsub(/\\/, '\\\\\\')}\");")
410 else
411 output.puts(" UnityBegin(\"#{filename.gsub(/\\/, '\\\\\\')}\");")
412 end
413 tests.each do |test|
414 if (!@options[:use_param_tests]) || test[:args].nil? || test[:args].empty?
415 output.puts(" run_test(#{test[:test]}, \"#{test[:test]}\", #{test[:line_number]});")
416 else
417 test[:args].each.with_index(1) do |args, idx|
418 wrapper = "runner_args#{idx}_#{test[:test]}"
419 testname = "#{test[:test]}(#{args})".dump
420 output.puts(" run_test(#{wrapper}, #{testname}, #{test[:line_number]});")
421 end
422 end
423 end
424 output.puts
425 output.puts(' CMock_Guts_MemFreeFinal();') unless used_mocks.empty?
426 if @options[:has_suite_teardown]
427 if @options[:omit_begin_end]
428 output.puts(' (void) suite_teardown(0);')
429 else
430 output.puts(' return suiteTearDown(UnityEnd());')
431 end
432 else
433 output.puts(' return UnityEnd();') unless @options[:omit_begin_end]
434 end
435 output.puts('}')
436 end
437
438 def create_h_file(output, filename, tests, testfile_includes, used_mocks)
439 filename = File.basename(filename).gsub(/[-\/\\\.\,\s]/, '_').upcase
440 output.puts('/* AUTOGENERATED FILE. DO NOT EDIT. */')
441 output.puts("#ifndef _#{filename}")
442 output.puts("#define _#{filename}\n\n")
443 output.puts("#include \"#{@options[:framework]}.h\"")
444 output.puts('#include "cmock.h"') unless used_mocks.empty?
445 @options[:includes].flatten.uniq.compact.each do |inc|
446 output.puts("#include #{inc.include?('<') ? inc : "\"#{inc}\""}")
447 end
448 testfile_includes.each do |inc|
449 output.puts("#include #{inc.include?('<') ? inc : "\"#{inc}\""}")
450 end
451 output.puts "\n"
452 tests.each do |test|
453 if test[:params].nil? || test[:params].empty?
454 output.puts("void #{test[:test]}(void);")
455 else
456 output.puts("void #{test[:test]}(#{test[:params]});")
457 end
458 end
459 output.puts("#endif\n\n")
460 end
461 end
462
463 if $0 == __FILE__
464 options = { includes: [] }
465
466 # parse out all the options first (these will all be removed as we go)
467 ARGV.reject! do |arg|
468 case arg
469 when '-cexception'
470 options[:plugins] = [:cexception]
471 true
472 when '-externcincludes'
473 options[:externcincludes] = true
474 true
475 when /\.*\.ya?ml$/
476 options = UnityTestRunnerGenerator.grab_config(arg)
477 true
478 when /--(\w+)=\"?(.*)\"?/
479 options[Regexp.last_match(1).to_sym] = Regexp.last_match(2)
480 true
481 when /\.*\.(?:hpp|hh|H|h)$/
482 options[:includes] << arg
483 true
484 else false
485 end
486 end
487
488 # make sure there is at least one parameter left (the input file)
489 unless ARGV[0]
490 puts ["\nusage: ruby #{__FILE__} (files) (options) input_test_file (output)",
491 "\n input_test_file - this is the C file you want to create a runner for",
492 ' output - this is the name of the runner file to generate',
493 ' defaults to (input_test_file)_Runner',
494 ' files:',
495 ' *.yml / *.yaml - loads configuration from here in :unity or :cmock',
496 ' *.h - header files are added as #includes in runner',
497 ' options:',
498 ' -cexception - include cexception support',
499 ' -externc - add extern "C" for cpp support',
500 ' --setup_name="" - redefine setUp func name to something else',
501 ' --teardown_name="" - redefine tearDown func name to something else',
502 ' --main_name="" - redefine main func name to something else',
503 ' --test_prefix="" - redefine test prefix from default test|spec|should',
504 ' --test_reset_name="" - redefine resetTest func name to something else',
505 ' --test_verify_name="" - redefine verifyTest func name to something else',
506 ' --suite_setup="" - code to execute for setup of entire suite',
507 ' --suite_teardown="" - code to execute for teardown of entire suite',
508 ' --use_param_tests=1 - enable parameterized tests (disabled by default)',
509 ' --omit_begin_end=1 - omit calls to UnityBegin and UnityEnd (disabled by default)',
510 ' --header_file="" - path/name of test header file to generate too'].join("\n")
511 exit 1
512 end
513
514 # create the default test runner name if not specified
515 ARGV[1] = ARGV[0].gsub('.c', '_Runner.c') unless ARGV[1]
516
517 UnityTestRunnerGenerator.new(options).run(ARGV[0], ARGV[1])
518 end