aboutsummaryrefslogtreecommitdiff
path: root/test/spec_tests.py
blob: d5b4d05a5ca6df3aa2531ab0a51985f0500a7108 (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. sys.stdout.buffer.write(err)
  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. l = line.strip()
  86. if l == "`" * 32 + " example":
  87. state = 1
  88. elif l == "`" * 32:
  89. 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 l == ".":
  103. state = 2
  104. elif state == 1:
  105. if start_line == 0:
  106. start_line = line_number - 1
  107. markdown_lines.append(line)
  108. elif state == 2:
  109. html_lines.append(line)
  110. elif state == 0 and re.match(header_re, line):
  111. headertext = header_re.sub('', line).strip()
  112. return tests
  113. if __name__ == "__main__":
  114. if args.debug_normalization:
  115. out(normalize_html(sys.stdin.read()))
  116. exit(0)
  117. all_tests = get_tests(args.spec)
  118. if args.pattern:
  119. pattern_re = re.compile(args.pattern, re.IGNORECASE)
  120. else:
  121. pattern_re = re.compile('.')
  122. tests = [ test for test in all_tests if re.search(pattern_re, test['section']) and (not args.number or test['example'] == args.number) ]
  123. if args.dump_tests:
  124. out(json.dumps(tests, ensure_ascii=False, indent=2))
  125. exit(0)
  126. else:
  127. skipped = len(all_tests) - len(tests)
  128. cmark = CMark(prog=args.program, library_dir=args.library_dir)
  129. result_counts = {'pass': 0, 'fail': 0, 'error': 0, 'skip': skipped}
  130. for test in tests:
  131. do_test(test, args.normalize, result_counts)
  132. out("{pass} passed, {fail} failed, {error} errored, {skip} skipped\n".format(**result_counts))
  133. if result_counts['fail'] == 0 and result_counts['error'] == 0:
  134. exit(0)
  135. else:
  136. exit(1)