aboutsummaryrefslogtreecommitdiff
path: root/test/spec_tests.py
blob: 182368ba8e7d94c5464f0bab60cd19781f13bf76 (plain)
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import sys
  4. from difflib import unified_diff
  5. import argparse
  6. import re
  7. import json
  8. from cmark import CMark
  9. from normalize import normalize_html
  10. if __name__ == "__main__":
  11. parser = argparse.ArgumentParser(description='Run cmark tests.')
  12. parser.add_argument('-p', '--program', dest='program', nargs='?', default=None,
  13. help='program to test')
  14. parser.add_argument('-s', '--spec', dest='spec', nargs='?', default='spec.txt',
  15. help='path to spec')
  16. parser.add_argument('-P', '--pattern', dest='pattern', nargs='?',
  17. default=None, help='limit to sections matching regex pattern')
  18. parser.add_argument('--library-dir', dest='library_dir', nargs='?',
  19. default=None, help='directory containing dynamic library')
  20. parser.add_argument('--no-normalize', dest='normalize',
  21. action='store_const', const=False, default=True,
  22. help='do not normalize HTML')
  23. parser.add_argument('-d', '--dump-tests', dest='dump_tests',
  24. action='store_const', const=True, default=False,
  25. help='dump tests in JSON format')
  26. parser.add_argument('--debug-normalization', dest='debug_normalization',
  27. action='store_const', const=True,
  28. default=False, help='filter stdin through normalizer for testing')
  29. parser.add_argument('-n', '--number', type=int, default=None,
  30. help='only consider the test with the given number')
  31. args = parser.parse_args(sys.argv[1:])
  32. def out(str):
  33. sys.stdout.buffer.write(str.encode('utf-8'))
  34. def print_test_header(headertext, example_number, start_line, end_line):
  35. out("Example %d (lines %d-%d) %s\n" % (example_number,start_line,end_line,headertext))
  36. def do_test(test, normalize, result_counts):
  37. [retcode, actual_html, err] = cmark.to_html(test['markdown'])
  38. if retcode == 0:
  39. expected_html = test['html']
  40. unicode_error = None
  41. if normalize:
  42. try:
  43. passed = normalize_html(actual_html) == normalize_html(expected_html)
  44. except UnicodeDecodeError as e:
  45. unicode_error = e
  46. passed = False
  47. else:
  48. passed = actual_html == expected_html
  49. if passed:
  50. result_counts['pass'] += 1
  51. else:
  52. print_test_header(test['section'], test['example'], test['start_line'], test['end_line'])
  53. out(test['markdown'] + '\n')
  54. if unicode_error:
  55. out("Unicode error: " + str(unicode_error) + '\n')
  56. out("Expected: " + repr(expected_html) + '\n')
  57. out("Got: " + repr(actual_html) + '\n')
  58. else:
  59. expected_html_lines = expected_html.splitlines(True)
  60. actual_html_lines = actual_html.splitlines(True)
  61. for diffline in unified_diff(expected_html_lines, actual_html_lines,
  62. "expected HTML", "actual HTML"):
  63. out(diffline)
  64. out('\n')
  65. result_counts['fail'] += 1
  66. else:
  67. print_test_header(test['section'], test['example'], test['start_line'], test['end_line'])
  68. out("program returned error code %d\n" % retcode)
  69. out(err + '\n')
  70. result_counts['error'] += 1
  71. def get_tests(specfile):
  72. line_number = 0
  73. start_line = 0
  74. end_line = 0
  75. example_number = 0
  76. markdown_lines = []
  77. html_lines = []
  78. state = 0 # 0 regular text, 1 markdown example, 2 html output
  79. headertext = ''
  80. tests = []
  81. header_re = re.compile('#+ ')
  82. with open(specfile, 'r', encoding='utf-8') as specf:
  83. for line in specf:
  84. line_number = line_number + 1
  85. if state == 0 and re.match(header_re, line):
  86. headertext = header_re.sub('', line).strip()
  87. if line.strip() == ".":
  88. state = (state + 1) % 3
  89. if state == 0:
  90. example_number = example_number + 1
  91. end_line = line_number
  92. tests.append({
  93. "markdown":''.join(markdown_lines).replace('→',"\t"),
  94. "html":''.join(html_lines).replace('→',"\t"),
  95. "example": example_number,
  96. "start_line": start_line,
  97. "end_line": end_line,
  98. "section": headertext})
  99. start_line = 0
  100. markdown_lines = []
  101. html_lines = []
  102. elif state == 1:
  103. if start_line == 0:
  104. start_line = line_number - 1
  105. markdown_lines.append(line)
  106. elif state == 2:
  107. html_lines.append(line)
  108. return tests
  109. if __name__ == "__main__":
  110. if args.debug_normalization:
  111. out(normalize_html(sys.stdin.read()))
  112. exit(0)
  113. all_tests = get_tests(args.spec)
  114. if args.pattern:
  115. pattern_re = re.compile(args.pattern, re.IGNORECASE)
  116. else:
  117. pattern_re = re.compile('.')
  118. tests = [ test for test in all_tests if re.search(pattern_re, test['section']) and (not args.number or test['example'] == args.number) ]
  119. if args.dump_tests:
  120. out(json.dumps(tests, ensure_ascii=False, indent=2))
  121. exit(0)
  122. else:
  123. skipped = len(all_tests) - len(tests)
  124. cmark = CMark(prog=args.program, library_dir=args.library_dir)
  125. result_counts = {'pass': 0, 'fail': 0, 'error': 0, 'skip': skipped}
  126. for test in tests:
  127. do_test(test, args.normalize, result_counts)
  128. out("{pass} passed, {fail} failed, {error} errored, {skip} skipped\n".format(**result_counts))
  129. if result_counts['fail'] == 0 and result_counts['error'] == 0:
  130. exit(0)
  131. else:
  132. exit(1)