run_sql_parser_test.py 3.7 KB

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