aboutsummaryrefslogtreecommitdiff
path: root/test/spec_tests.py
blob: aa172a0294ab8073ef9078a996c0847a8fcb59fa (plain)
  1. #!/usr/bin/env python2
  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 print_test_header(headertext, example_number, start_line, end_line):
  33. print "Example %d (lines %d-%d) %s" % (example_number,start_line,end_line,headertext)
  34. def do_test(test, normalize, result_counts):
  35. [retcode, actual_html, err] = cmark.to_html(test['markdown'])
  36. if retcode == 0:
  37. expected_html = test['html']
  38. unicode_error = None
  39. if normalize:
  40. try:
  41. passed = normalize_html(actual_html) == normalize_html(expected_html)
  42. except UnicodeDecodeError, e:
  43. unicode_error = e
  44. passed = False
  45. else:
  46. passed = actual_html == expected_html
  47. if passed:
  48. result_counts['pass'] += 1
  49. else:
  50. print_test_header(test['section'], test['example'], test['start_line'], test['end_line'])
  51. sys.stdout.write(test['markdown'])
  52. if unicode_error:
  53. print "Unicode error: " + str(unicode_error)
  54. print "Expected: " + repr(expected_html)
  55. print "Got: " + repr(actual_html)
  56. else:
  57. expected_html_lines = expected_html.splitlines(True)
  58. actual_html_lines = actual_html.splitlines(True)
  59. for diffline in unified_diff(expected_html_lines, actual_html_lines,
  60. "expected HTML", "actual HTML"):
  61. sys.stdout.write(diffline)
  62. sys.stdout.write('\n')
  63. result_counts['fail'] += 1
  64. else:
  65. print_test_header(test['section'], test['example'], test['start_line'], test['end_line'])
  66. print "program returned error code %d" % retcode
  67. print(err)
  68. result_counts['error'] += 1
  69. def get_tests(specfile):
  70. line_number = 0
  71. start_line = 0
  72. end_line = 0
  73. example_number = 0
  74. markdown_lines = []
  75. html_lines = []
  76. state = 0 # 0 regular text, 1 markdown example, 2 html output
  77. headertext = ''
  78. tests = []
  79. header_re = re.compile('#+ ')
  80. with open(specfile, 'r') as specf:
  81. for line in specf:
  82. line_number = line_number + 1
  83. if state == 0 and re.match(header_re, line):
  84. headertext = header_re.sub('', line).strip()
  85. if line.strip() == ".":
  86. state = (state + 1) % 3
  87. if state == 0:
  88. example_number = example_number + 1
  89. end_line = line_number
  90. tests.append({
  91. "markdown":''.join(markdown_lines).replace('→',"\t"),
  92. "html":''.join(html_lines),
  93. "example": example_number,
  94. "start_line": start_line,
  95. "end_line": end_line,
  96. "section": headertext})
  97. start_line = 0
  98. markdown_lines = []
  99. html_lines = []
  100. elif state == 1:
  101. if start_line == 0:
  102. start_line = line_number - 1
  103. markdown_lines.append(line)
  104. elif state == 2:
  105. html_lines.append(line)
  106. return tests
  107. if __name__ == "__main__":
  108. if args.debug_normalization:
  109. print normalize_html(sys.stdin.read())
  110. exit(0)
  111. all_tests = get_tests(args.spec)
  112. if args.pattern:
  113. pattern_re = re.compile(args.pattern, re.IGNORECASE)
  114. else:
  115. pattern_re = re.compile('.')
  116. tests = [ test for test in all_tests if re.search(pattern_re, test['section']) and (not args.number or test['example'] == args.number) ]
  117. if args.dump_tests:
  118. print json.dumps(tests, ensure_ascii=False, indent=2)
  119. exit(0)
  120. else:
  121. skipped = len(all_tests) - len(tests)
  122. cmark = CMark(prog=args.program, library_dir=args.library_dir)
  123. result_counts = {'pass': 0, 'fail': 0, 'error': 0, 'skip': skipped}
  124. for test in tests:
  125. do_test(test, args.normalize, result_counts)
  126. print "{pass} passed, {fail} failed, {error} errored, {skip} skipped".format(**result_counts)
  127. if result_counts['fail'] == 0 and result_counts['error'] == 0:
  128. exit(0)
  129. else:
  130. exit(1)