A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 

171 satır
6.1 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.compat import py3k
  39. from mwparserfromhell.parser._tokenizer import CTokenizer
  40. if sys.version_info[0] == 2:
  41. range = xrange
  42. LOOPS = 10000
  43. class Color(object):
  44. GRAY = "\x1b[30;1m"
  45. GREEN = "\x1b[92m"
  46. YELLOW = "\x1b[93m"
  47. RESET = "\x1b[0m"
  48. class MemoryTest(object):
  49. """Manages a memory test."""
  50. def __init__(self):
  51. self._tests = []
  52. self._load()
  53. def _parse_file(self, name, text):
  54. tests = text.split("\n---\n")
  55. counter = 1
  56. digits = len(str(len(tests)))
  57. for test in tests:
  58. data = {"name": None, "label": None, "input": None, "output": None}
  59. for line in test.strip().splitlines():
  60. if line.startswith("name:"):
  61. data["name"] = line[len("name:"):].strip()
  62. elif line.startswith("label:"):
  63. data["label"] = line[len("label:"):].strip()
  64. elif line.startswith("input:"):
  65. raw = line[len("input:"):].strip()
  66. if raw[0] == '"' and raw[-1] == '"':
  67. raw = raw[1:-1]
  68. raw = raw.encode("raw_unicode_escape")
  69. data["input"] = raw.decode("unicode_escape")
  70. number = str(counter).zfill(digits)
  71. fname = "test_{}{}_{}".format(name, number, data["name"])
  72. self._tests.append((fname, data["input"]))
  73. counter += 1
  74. def _load(self):
  75. def load_file(filename):
  76. with open(filename, "rU") as fp:
  77. text = fp.read()
  78. if not py3k:
  79. text = text.decode("utf8")
  80. name = path.split(filename)[1][:0-len(extension)]
  81. self._parse_file(name, text)
  82. root = path.split(path.dirname(path.abspath(__file__)))[0]
  83. directory = path.join(root, "tests", "tokenizer")
  84. extension = ".mwtest"
  85. if len(sys.argv) > 2 and sys.argv[1] == "--use":
  86. for name in sys.argv[2:]:
  87. load_file(path.join(directory, name + extension))
  88. sys.argv = [sys.argv[0]] # So unittest doesn't try to load these
  89. else:
  90. for filename in listdir(directory):
  91. if not filename.endswith(extension):
  92. continue
  93. load_file(path.join(directory, filename))
  94. @staticmethod
  95. def _print_results(info1, info2):
  96. r1, r2 = info1.rss, info2.rss
  97. buff = 8192
  98. if r2 - buff > r1:
  99. d = r2 - r1
  100. p = float(d) / r1
  101. bpt = d // LOOPS
  102. tmpl = "{0}LEAKING{1}: {2:n} bytes, {3:.2%} inc ({4:n} bytes/loop)"
  103. sys.stdout.write(tmpl.format(Color.YELLOW, Color.RESET, d, p, bpt))
  104. else:
  105. sys.stdout.write("{}OK{}".format(Color.GREEN, Color.RESET))
  106. def run(self):
  107. """Run the memory test suite."""
  108. width = 1
  109. for (name, _) in self._tests:
  110. if len(name) > width:
  111. width = len(name)
  112. tmpl = "{0}[{1:03}/{2}]{3} {4}: "
  113. for i, (name, text) in enumerate(self._tests, 1):
  114. sys.stdout.write(tmpl.format(Color.GRAY, i, len(self._tests),
  115. Color.RESET, name.ljust(width)))
  116. sys.stdout.flush()
  117. parent, child = Pipe()
  118. p = Process(target=_runner, args=(text, child))
  119. p.start()
  120. try:
  121. proc = psutil.Process(p.pid)
  122. parent.recv()
  123. parent.send("OK")
  124. parent.recv()
  125. info1 = proc.get_memory_info()
  126. sys.stdout.flush()
  127. parent.send("OK")
  128. parent.recv()
  129. info2 = proc.get_memory_info()
  130. self._print_results(info1, info2)
  131. sys.stdout.flush()
  132. parent.send("OK")
  133. finally:
  134. proc.kill()
  135. print()
  136. def _runner(text, child):
  137. r1, r2 = range(250), range(LOOPS)
  138. for i in r1:
  139. CTokenizer().tokenize(text)
  140. child.send("OK")
  141. child.recv()
  142. child.send("OK")
  143. child.recv()
  144. for i in r2:
  145. CTokenizer().tokenize(text)
  146. child.send("OK")
  147. child.recv()
  148. if __name__ == "__main__":
  149. setlocale(LC_ALL, "")
  150. MemoryTest().run()