aboutsummaryrefslogtreecommitdiff
path: root/runtests.py
blob: 601508dc91ecd87c336436706a7ccd118b2f2dfc (plain)
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from ctypes import CDLL, c_char_p, c_long
  4. import sys
  5. import platform
  6. from difflib import unified_diff
  7. from subprocess import *
  8. import argparse
  9. from HTMLParser import HTMLParser, HTMLParseError
  10. from htmlentitydefs import name2codepoint
  11. import re
  12. import cgi
  13. import json
  14. if __name__ == "__main__":
  15. parser = argparse.ArgumentParser(description='Run cmark tests.')
  16. parser.add_argument('--program', dest='program', nargs='?', default=None,
  17. help='program to test')
  18. parser.add_argument('--spec', dest='spec', nargs='?', default='spec.txt',
  19. help='path to spec')
  20. parser.add_argument('--pattern', dest='pattern', nargs='?',
  21. default=None, help='limit to sections matching regex pattern')
  22. parser.add_argument('--library-dir', dest='library_dir', nargs='?',
  23. default=None, help='directory containing dynamic library')
  24. parser.add_argument('--no-normalize', dest='normalize',
  25. action='store_const', const=False, default=True,
  26. help='do not normalize HTML')
  27. parser.add_argument('--dump-tests', dest='dump_tests',
  28. action='store_const', const=True, default=False,
  29. help='dump tests in JSON format')
  30. parser.add_argument('--debug-normalization', dest='debug_normalization',
  31. action='store_const', const=True,
  32. default=False, help='filter stdin through normalizer for testing')
  33. args = parser.parse_args(sys.argv[1:])
  34. if not (args.program or args.dump_tests or args.debug_normalization):
  35. sysname = platform.system()
  36. libname = "libcmark"
  37. if sysname == 'Darwin':
  38. libname += ".dylib"
  39. elif sysname == 'Windows':
  40. libname += ".dll"
  41. else:
  42. libname += ".so"
  43. if args and args.library_dir:
  44. libpath = args.library_dir + "/" + libname
  45. else:
  46. libpath = "build/src/" + libname
  47. cmark = CDLL(libpath)
  48. markdown = cmark.cmark_markdown_to_html
  49. markdown.restype = c_char_p
  50. markdown.argtypes = [c_char_p, c_long]
  51. def md2html(text, prog):
  52. if prog:
  53. p1 = Popen([prog], stdout=PIPE, stdin=PIPE, stderr=PIPE)
  54. [result, err] = p1.communicate(input=text)
  55. return [p1.returncode, result, err]
  56. else:
  57. return [0, markdown(text, len(text)), '']
  58. # Normalization code, adapted from
  59. # https://github.com/karlcow/markdown-testsuite/
  60. significant_attrs = ["alt", "href", "src", "title"]
  61. normalize_whitespace_re = re.compile('\s+')
  62. class MyHTMLParser(HTMLParser):
  63. def __init__(self):
  64. HTMLParser.__init__(self)
  65. self.last = "starttag"
  66. self.in_pre = False
  67. self.output = u""
  68. self.last_tag = ""
  69. def handle_data(self, data):
  70. after_tag = self.last == "endtag" or self.last == "starttag"
  71. after_block_tag = after_tag and self.is_block_tag(self.last_tag)
  72. if after_tag and self.last_tag == "br":
  73. data = data.lstrip('\n')
  74. data = normalize_whitespace_re.sub(' ', data)
  75. if after_block_tag and not self.in_pre:
  76. if self.last == "starttag":
  77. data = data.lstrip()
  78. elif self.last == "endtag":
  79. data = data.strip()
  80. self.output += data
  81. self.last = "data"
  82. def handle_endtag(self, tag):
  83. if tag == "pre":
  84. self.in_pre = False
  85. if self.is_block_tag(tag):
  86. self.output = self.output.rstrip()
  87. self.output += "</" + tag + ">"
  88. self.last_tag = tag
  89. self.last = "endtag"
  90. def handle_starttag(self, tag, attrs):
  91. if tag == "pre":
  92. self.in_pre = True
  93. self.output += "<" + tag
  94. # For now we don't strip out 'extra' attributes, because of
  95. # raw HTML test cases.
  96. # attrs = filter(lambda attr: attr[0] in significant_attrs, attrs)
  97. if attrs:
  98. attrs.sort()
  99. for (k,v) in attrs:
  100. self.output += " " + k
  101. if v != None:
  102. self.output += ("=" + '"' + cgi.escape(v,quote=True) + '"')
  103. self.output += ">"
  104. self.last_tag = tag
  105. self.last = "starttag"
  106. def handle_startendtag(self, tag, attrs):
  107. """Ignore closing tag for self-closing """
  108. self.handle_starttag(tag, attrs)
  109. self.last_tag = tag
  110. self.last = "endtag"
  111. def handle_comment(self, data):
  112. self.output += '<!--' + data + '-->'
  113. self.last = "comment"
  114. def handle_decl(self, data):
  115. self.output += '<!' + data + '>'
  116. self.last = "decl"
  117. def unknown_decl(self, data):
  118. self.output += '<!' + data + '>'
  119. self.last = "decl"
  120. def handle_pi(self,data):
  121. self.output += '<?' + data + '>'
  122. self.last = "pi"
  123. def handle_entityref(self, name):
  124. try:
  125. c = unichr(name2codepoint[name])
  126. except KeyError:
  127. c = None
  128. self.output_char(c, '&' + name + ';')
  129. self.last = "ref"
  130. def handle_charref(self, name):
  131. try:
  132. if name.startswith("x"):
  133. c = unichr(int(name[1:], 16))
  134. else:
  135. c = unichr(int(name))
  136. except ValueError:
  137. c = None
  138. self.output_char(c, '&' + name + ';')
  139. self.last = "ref"
  140. # Helpers.
  141. def output_char(self, c, fallback):
  142. if c == u'<':
  143. self.output += "&lt;"
  144. elif c == u'>':
  145. self.output += "&gt;"
  146. elif c == u'&':
  147. self.output += "&amp;"
  148. elif c == u'"':
  149. self.output += "&quot;"
  150. elif c == None:
  151. self.output += fallback
  152. else:
  153. self.output += c
  154. def is_block_tag(self,tag):
  155. return (tag in ['article', 'header', 'aside', 'hgroup', 'blockquote',
  156. 'hr', 'iframe', 'body', 'li', 'map', 'button', 'object', 'canvas',
  157. 'ol', 'caption', 'output', 'col', 'p', 'colgroup', 'pre', 'dd',
  158. 'progress', 'div', 'section', 'dl', 'table', 'td', 'dt',
  159. 'tbody', 'embed', 'textarea', 'fieldset', 'tfoot', 'figcaption',
  160. 'th', 'figure', 'thead', 'footer', 'tr', 'form', 'ul',
  161. 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'video', 'script', 'style'])
  162. def normalize_html(html):
  163. r"""
  164. Return normalized form of HTML which ignores insignificant output
  165. differences:
  166. * Multiple inner whitespaces are collapsed to a single space (except
  167. in pre tags).
  168. * Outer whitespace (outside block-level tags) is removed.
  169. * Self-closing tags are converted to open tags.
  170. * Attributes are sorted and lowercased.
  171. * References are converted to unicode, except that '<', '>', '&', and
  172. '&' are rendered using entities.
  173. """
  174. html_chunk_re = re.compile("(\<!\[CDATA\[.*?\]\]\>|\<[^>]*\>|[^<]+)")
  175. try:
  176. parser = MyHTMLParser()
  177. # We work around HTMLParser's limitations parsing CDATA
  178. # by breaking the input into chunks and passing CDATA chunks
  179. # through verbatim.
  180. for chunk in re.finditer(html_chunk_re, html):
  181. if chunk.group(0)[:8] == "<![CDATA":
  182. parser.output += chunk.group(0)
  183. else:
  184. parser.feed(chunk.group(0).decode(encoding='UTF-8'))
  185. parser.close()
  186. return parser.output
  187. except HTMLParseError as e:
  188. sys.stderr.write("Normalization error: " + e.msg + "\n")
  189. return html # on error, return unnormalized HTML
  190. def print_test_header(headertext, example_number, start_line, end_line):
  191. print "Example %d (lines %d-%d) %s" % (example_number,start_line,end_line,headertext)
  192. def do_test(markdown_lines, expected_html_lines, headertext,
  193. example_number, start_line, end_line, prog, normalize):
  194. real_markdown_text = ''.join(markdown_lines).replace('→','\t')
  195. [retcode, actual_html, err] = md2html(real_markdown_text, prog)
  196. if retcode == 0:
  197. actual_html_lines = actual_html.splitlines(True)
  198. expected_html = ''.join(expected_html_lines)
  199. if normalize:
  200. passed = normalize_html(actual_html) == normalize_html(expected_html)
  201. else:
  202. passed = actual_html == expected_html
  203. if passed:
  204. return 'pass'
  205. else:
  206. print_test_header(headertext, example_number,start_line,end_line)
  207. sys.stdout.write(real_markdown_text)
  208. for diffline in unified_diff(expected_html_lines, actual_html_lines,
  209. "expected HTML", "actual HTML"):
  210. sys.stdout.write(diffline)
  211. sys.stdout.write('\n')
  212. return 'fail'
  213. else:
  214. print_test_header(headertext, example_number, start_line, end_line)
  215. print "program returned error code %d" % retcode
  216. print(err)
  217. return 'error'
  218. def do_tests(specfile, prog, pattern, normalize, dump_tests):
  219. line_number = 0
  220. start_line = 0
  221. end_line = 0
  222. example_number = 0
  223. passed = 0
  224. failed = 0
  225. errored = 0
  226. markdown_lines = []
  227. html_lines = []
  228. active = True
  229. state = 0 # 0 regular text, 1 markdown example, 2 html output
  230. headertext = ''
  231. tests_json = []
  232. header_re = re.compile('#+ ')
  233. if pattern:
  234. pattern_re = re.compile(pattern, re.IGNORECASE)
  235. with open(specfile, 'r') as specf:
  236. for line in specf:
  237. line_number = line_number + 1
  238. if state == 0 and re.match(header_re, line):
  239. headertext = header_re.sub('', line).strip()
  240. if pattern:
  241. if re.search(pattern_re, line):
  242. active = True
  243. else:
  244. active = False
  245. if line.strip() == ".":
  246. state = (state + 1) % 3
  247. if state == 0:
  248. example_number = example_number + 1
  249. end_line = line_number
  250. if active:
  251. if dump_tests:
  252. tests_json.append({
  253. "markdown":''.join(markdown_lines),
  254. "html":''.join(html_lines),
  255. "example": example_number,
  256. "start_line": start_line,
  257. "end_line": end_line,
  258. "section": headertext})
  259. else:
  260. result = do_test(markdown_lines, html_lines,
  261. headertext, example_number,
  262. start_line, end_line, prog,
  263. normalize)
  264. if result == 'pass':
  265. passed = passed + 1
  266. elif result == 'fail':
  267. failed = failed + 1
  268. else:
  269. errored = errored + 1
  270. start_line = 0
  271. markdown_lines = []
  272. html_lines = []
  273. elif state == 1:
  274. if start_line == 0:
  275. start_line = line_number - 1
  276. markdown_lines.append(line)
  277. elif state == 2:
  278. html_lines.append(line)
  279. if dump_tests:
  280. print json.dumps(tests_json, ensure_ascii=False, indent=2)
  281. else:
  282. print "%d passed, %d failed, %d errored" % (passed, failed, errored)
  283. return (failed == 0 and errored == 0)
  284. if __name__ == "__main__":
  285. if args.debug_normalization:
  286. print normalize_html(sys.stdin.read())
  287. elif do_tests(args.spec, args.program, args.pattern, args.normalize,
  288. args.dump_tests):
  289. exit(0)
  290. else:
  291. exit(1)