testcpp.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. from unittest import TestCase, main
  2. from multiprocessing import Process, Queue
  3. from six.moves.queue import Empty
  4. import sys
  5. if ".." not in sys.path:
  6. sys.path.insert(0, "..")
  7. from ply.lex import lex
  8. from ply.cpp import *
  9. def preprocessing(in_, out_queue):
  10. out = None
  11. try:
  12. p = Preprocessor(lex())
  13. p.parse(in_)
  14. tokens = [t.value for t in p.parser]
  15. out = "".join(tokens)
  16. finally:
  17. out_queue.put(out)
  18. class CPPTests(TestCase):
  19. "Tests related to ANSI-C style lexical preprocessor."
  20. def __test_preprocessing(self, in_, expected, time_limit = 1.0):
  21. out_queue = Queue()
  22. preprocessor = Process(
  23. name = "PLY`s C preprocessor",
  24. target = preprocessing,
  25. args = (in_, out_queue)
  26. )
  27. preprocessor.start()
  28. try:
  29. out = out_queue.get(timeout = time_limit)
  30. except Empty:
  31. preprocessor.terminate()
  32. raise RuntimeError("Time limit exceeded!")
  33. else:
  34. self.assertMultiLineEqual(out, expected)
  35. def test_concatenation(self):
  36. self.__test_preprocessing("""\
  37. #define a(x) x##_
  38. #define b(x) _##x
  39. #define c(x) _##x##_
  40. #define d(x,y) _##x##y##_
  41. a(i)
  42. b(j)
  43. c(k)
  44. d(q,s)"""
  45. , """\
  46. i_
  47. _j
  48. _k_
  49. _qs_"""
  50. )
  51. def test_deadloop_macro(self):
  52. # If there is a word which equals to name of a parametrized macro, then
  53. # attempt to expand such word as a macro manages the parser to fall
  54. # into an infinite loop.
  55. self.__test_preprocessing("""\
  56. #define a(x) x
  57. a;"""
  58. , """\
  59. a;"""
  60. )
  61. def test_index_error(self):
  62. # If there are no tokens after a word ("a") which equals to name of
  63. # a parameterized macro, then attempt to expand this word leads to
  64. # IndexError.
  65. self.__test_preprocessing("""\
  66. #define a(x) x
  67. a"""
  68. , """\
  69. a"""
  70. )
  71. main()