A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 

162 行
5.8 KiB

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