1
0

benchmarks.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. """Runs the benchmarks and inserts the results into the database."""
  2. import json
  3. import os
  4. import sys
  5. import pytest
  6. from helpers import insert_benchmarking_data
  7. def get_lighthouse_scores(directory_path: str) -> dict:
  8. """Extracts the Lighthouse scores from the JSON files in the specified directory.
  9. Args:
  10. directory_path (str): The path to the directory containing the JSON files.
  11. Returns:
  12. dict: The Lighthouse scores.
  13. """
  14. scores = {}
  15. try:
  16. for filename in os.listdir(directory_path):
  17. if filename.endswith(".json") and filename != "manifest.json":
  18. file_path = os.path.join(directory_path, filename)
  19. with open(file_path, "r") as file:
  20. data = json.load(file)
  21. # Extract scores and add them to the dictionary with the filename as key
  22. scores[data["finalUrl"].replace("http://localhost:3000/", "")] = {
  23. "performance_score": data["categories"]["performance"]["score"],
  24. "accessibility_score": data["categories"]["accessibility"][
  25. "score"
  26. ],
  27. "best_practices_score": data["categories"]["best-practices"][
  28. "score"
  29. ],
  30. "seo_score": data["categories"]["seo"]["score"],
  31. "pwa_score": data["categories"]["pwa"]["score"],
  32. }
  33. except Exception as e:
  34. print(e)
  35. return {"error": "Error parsing JSON files"}
  36. return scores
  37. def run_pytest_and_get_results(test_path=None) -> dict:
  38. """Runs pytest and returns the results.
  39. Args:
  40. test_path: The path to the tests to run.
  41. Returns:
  42. dict: The results of the tests.
  43. """
  44. # Set the default path to the current directory if no path is provided
  45. if not test_path:
  46. test_path = os.getcwd()
  47. # Ensure you have installed the pytest-json plugin before running this
  48. pytest_args = ["-v", "--benchmark-json=benchmark_report.json", test_path]
  49. # Run pytest with the specified arguments
  50. pytest.main(pytest_args)
  51. # Print ls of the current directory
  52. print(os.listdir())
  53. with open("benchmark_report.json", "r") as file:
  54. pytest_results = json.load(file)
  55. return pytest_results
  56. def extract_stats_from_json(json_data) -> list[dict]:
  57. """Extracts the stats from the JSON data and returns them as a list of dictionaries.
  58. Args:
  59. json_data: The JSON data to extract the stats from.
  60. Returns:
  61. list[dict]: The stats for each test.
  62. """
  63. # Load the JSON data if it is a string, otherwise assume it's already a dictionary
  64. data = json.loads(json_data) if isinstance(json_data, str) else json_data
  65. # Initialize an empty list to store the stats for each test
  66. test_stats = []
  67. # Iterate over each test in the 'benchmarks' list
  68. for test in data.get("benchmarks", []):
  69. stats = test.get("stats", {})
  70. test_name = test.get("name", "Unknown Test")
  71. min_value = stats.get("min", None)
  72. max_value = stats.get("max", None)
  73. mean_value = stats.get("mean", None)
  74. stdev_value = stats.get("stddev", None)
  75. test_stats.append(
  76. {
  77. "test_name": test_name,
  78. "min": min_value,
  79. "max": max_value,
  80. "mean": mean_value,
  81. "stdev": stdev_value,
  82. }
  83. )
  84. return test_stats
  85. def main():
  86. """Runs the benchmarks and inserts the results into the database."""
  87. # Get the commit SHA and JSON directory from the command line arguments
  88. commit_sha = sys.argv[1]
  89. json_dir = sys.argv[2]
  90. # Get the PR title and database URL from the environment variables
  91. pr_title = os.environ.get("PR_TITLE")
  92. db_url = os.environ.get("DATABASE_URL")
  93. if db_url is None or pr_title is None:
  94. sys.exit("Missing environment variables")
  95. # Run pytest and get the results
  96. results = run_pytest_and_get_results()
  97. cleaned_results = extract_stats_from_json(results)
  98. # Get the Lighthouse scores
  99. lighthouse_scores = get_lighthouse_scores(json_dir)
  100. # Insert the data into the database
  101. insert_benchmarking_data(
  102. db_url, lighthouse_scores, cleaned_results, commit_sha, pr_title
  103. )
  104. if __name__ == "__main__":
  105. main()