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