A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

168 regels
6.0 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012-2016 Ben Kurtovic <ben.kurtovic@gmail.com>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. """
  23. Tests for memory leaks in the CTokenizer. Python 2 and 3 compatible.
  24. This appears to work mostly fine under Linux, but gives an absurd number of
  25. false positives on OS X. I'm not sure why. Running the tests multiple times
  26. yields different results (tests don't always leak, and the amount they leak by
  27. varies). Increasing the number of loops results in a smaller bytes/loop value,
  28. too, indicating the increase in memory usage might be due to something else.
  29. Actual memory leaks typically leak very large amounts of memory (megabytes)
  30. and scale with the number of loops.
  31. """
  32. from __future__ import unicode_literals, print_function
  33. from locale import LC_ALL, setlocale
  34. from multiprocessing import Process, Pipe
  35. from os import listdir, path
  36. import sys
  37. import psutil
  38. from mwparserfromhell.parser._tokenizer import CTokenizer
  39. if sys.version_info[0] == 2:
  40. range = xrange
  41. LOOPS = 10000
  42. class Color(object):
  43. GRAY = "\x1b[30;1m"
  44. GREEN = "\x1b[92m"
  45. YELLOW = "\x1b[93m"
  46. RESET = "\x1b[0m"
  47. class MemoryTest(object):
  48. """Manages a memory test."""
  49. def __init__(self):
  50. self._tests = []
  51. self._load()
  52. def _parse_file(self, name, text):
  53. tests = text.split("\n---\n")
  54. counter = 1
  55. digits = len(str(len(tests)))
  56. for test in tests:
  57. data = {"name": None, "label": None, "input": None, "output": None}
  58. for line in test.strip().splitlines():
  59. if line.startswith("name:"):
  60. data["name"] = line[len("name:"):].strip()
  61. elif line.startswith("label:"):
  62. data["label"] = line[len("label:"):].strip()
  63. elif line.startswith("input:"):
  64. raw = line[len("input:"):].strip()
  65. if raw[0] == '"' and raw[-1] == '"':
  66. raw = raw[1:-1]
  67. raw = raw.encode("raw_unicode_escape")
  68. data["input"] = raw.decode("unicode_escape")
  69. number = str(counter).zfill(digits)
  70. fname = "test_{}{}_{}".format(name, number, data["name"])
  71. self._tests.append((fname, data["input"]))
  72. counter += 1
  73. def _load(self):
  74. def load_file(filename):
  75. with open(filename, "rU") as fp:
  76. text = fp.read()
  77. name = path.split(filename)[1][:0-len(extension)]
  78. self._parse_file(name, text)
  79. root = path.split(path.dirname(path.abspath(__file__)))[0]
  80. directory = path.join(root, "tests", "tokenizer")
  81. extension = ".mwtest"
  82. if len(sys.argv) > 2 and sys.argv[1] == "--use":
  83. for name in sys.argv[2:]:
  84. load_file(path.join(directory, name + extension))
  85. sys.argv = [sys.argv[0]] # So unittest doesn't try to load these
  86. else:
  87. for filename in listdir(directory):
  88. if not filename.endswith(extension):
  89. continue
  90. load_file(path.join(directory, filename))
  91. @staticmethod
  92. def _print_results(info1, info2):
  93. r1, r2 = info1.rss, info2.rss
  94. buff = 8192
  95. if r2 - buff > r1:
  96. d = r2 - r1
  97. p = float(d) / r1
  98. bpt = d // LOOPS
  99. tmpl = "{0}LEAKING{1}: {2:n} bytes, {3:.2%} inc ({4:n} bytes/loop)"
  100. sys.stdout.write(tmpl.format(Color.YELLOW, Color.RESET, d, p, bpt))
  101. else:
  102. sys.stdout.write("{}OK{}".format(Color.GREEN, Color.RESET))
  103. def run(self):
  104. """Run the memory test suite."""
  105. width = 1
  106. for (name, _) in self._tests:
  107. if len(name) > width:
  108. width = len(name)
  109. tmpl = "{0}[{1:03}/{2}]{3} {4}: "
  110. for i, (name, text) in enumerate(self._tests, 1):
  111. sys.stdout.write(tmpl.format(Color.GRAY, i, len(self._tests),
  112. Color.RESET, name.ljust(width)))
  113. sys.stdout.flush()
  114. parent, child = Pipe()
  115. p = Process(target=_runner, args=(text, child))
  116. p.start()
  117. try:
  118. proc = psutil.Process(p.pid)
  119. parent.recv()
  120. parent.send("OK")
  121. parent.recv()
  122. info1 = proc.get_memory_info()
  123. sys.stdout.flush()
  124. parent.send("OK")
  125. parent.recv()
  126. info2 = proc.get_memory_info()
  127. self._print_results(info1, info2)
  128. sys.stdout.flush()
  129. parent.send("OK")
  130. finally:
  131. proc.kill()
  132. print()
  133. def _runner(text, child):
  134. r1, r2 = range(250), range(LOOPS)
  135. for i in r1:
  136. CTokenizer().tokenize(text)
  137. child.send("OK")
  138. child.recv()
  139. child.send("OK")
  140. child.recv()
  141. for i in r2:
  142. CTokenizer().tokenize(text)
  143. child.send("OK")
  144. child.recv()
  145. if __name__ == "__main__":
  146. setlocale(LC_ALL, "")
  147. MemoryTest().run()