run_sql_parser_test.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. from pathlib import Path
  2. import asyncio.subprocess as subprocess
  3. import asyncio
  4. from watchfiles import awatch
  5. from termcolor import colored
  6. from datetime import datetime
  7. import orjson
  8. import os
  9. import tempfile
  10. import tests_config
  11. import importlib
  12. importlib.reload(tests_config)
  13. sql_parser_tests, sql_checker_tests = tests_config.sql_parser_tests, tests_config.sql_checker_tests
  14. async def run_and_output(
  15. *args: str, timeout=10
  16. ) -> tuple[bytes, bytes]:
  17. p = await subprocess.create_subprocess_exec(
  18. *args,
  19. stdout=subprocess.PIPE,
  20. stderr=subprocess.PIPE,
  21. )
  22. stdout, stderr = await asyncio.wait_for(p.communicate(), timeout=timeout)
  23. return stdout, stderr
  24. async def rebuild() -> bool:
  25. print(datetime.now(), colored('rebuild...', "grey"))
  26. stdout, _ = await run_and_output('xmake')
  27. if b"error" in stdout:
  28. print(stdout.decode("utf-8"))
  29. print(datetime.now(), "-" * 40)
  30. return False
  31. else:
  32. return True
  33. async def assert_sql(sql: str, expected: dict):
  34. stdout, stderr = await run_and_output('xmake', 'run', "sql-parser", sql)
  35. if b"error" in stdout:
  36. print(stdout.decode("utf-8"))
  37. print(datetime.now(), "-" * 40)
  38. print(f'other: {colored(stderr.decode("utf-8"), "yellow")}')
  39. assert False, "sql-parser error"
  40. try:
  41. output = orjson.loads(stdout)
  42. except Exception as e:
  43. output = {"error": e, "output": stdout.decode("utf-8")}
  44. open("/tmp/temp/test.py", "wb").write(
  45. f'"{sql}"\n\n'.encode("utf-8")
  46. + orjson.dumps(output, option=orjson.OPT_INDENT_2)
  47. + (b"\n\n" + stderr).replace(b"\n", b"\n# ")
  48. )
  49. assert (
  50. output == expected
  51. ), f"""{colored("sql-parser error", "red")}
  52. input: {colored(sql, "yellow")}
  53. expect: {colored(expected, "green")}
  54. actual: {colored(output, "red")}
  55. other: {colored(stderr.decode("utf-8"), "yellow")}
  56. """
  57. async def assert_sqls():
  58. for sql, excepted in sql_parser_tests:
  59. await assert_sql(sql, excepted)
  60. async def on_parser_modified():
  61. print(datetime.now(), colored("run parser tests...", "yellow"))
  62. try:
  63. await assert_sqls()
  64. except Exception as e:
  65. print(e)
  66. else:
  67. print(datetime.now(), colored("all parser tests right!", "green"))
  68. async def assert_checks():
  69. for sql, res in sql_checker_tests:
  70. stdout, stderr = await run_and_output(
  71. 'xmake', 'run', "sql-checker",
  72. "-s", sql
  73. )
  74. print(sql, res)
  75. if res is True:
  76. assert b'error' not in stdout, stdout.decode("utf-8")
  77. assert b'error' not in stderr, stderr.decode('utf-8')
  78. elif isinstance(res, str):
  79. res = res.encode('utf-8')
  80. assert res in stderr, stderr.decode("utf-8")
  81. else:
  82. assert False, f"{res} 不是合适的结果"
  83. async def on_checker_modified():
  84. print(datetime.now(), colored("run checker tests...", "yellow"))
  85. try:
  86. await assert_checks()
  87. except Exception as e:
  88. print(e)
  89. print(datetime.now(), colored("all checker tests right!", "green"))
  90. async def restart():
  91. async for _ in awatch(__file__, "./tests_config.py"):
  92. print("restart")
  93. os.execl("/bin/python", Path(__file__).as_posix(), Path(__file__).as_posix())
  94. async def watch_parser():
  95. async for changes in awatch("./src/parser.y", "./src/parser.l"):
  96. if await rebuild():
  97. await asyncio.wait_for(on_parser_modified(), 10)
  98. async def watch_checker():
  99. async for changes in awatch("./src/checker.cpp", "./src/checker.h", "./src/utils.h", "./src/utils.cpp"):
  100. if await rebuild():
  101. await on_checker_modified()
  102. async def main():
  103. await asyncio.gather(
  104. restart(),
  105. watch_parser(),
  106. watch_checker(),
  107. on_parser_modified(),
  108. on_checker_modified(),
  109. )
  110. if __name__ == "__main__":
  111. asyncio.run(main())