generate_test_runner.rb 20 KB

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